【问题标题】:T-SQL - how to select rows distinct and move one row to columnT-SQL - 如何选择不同的行并将一行移动到列
【发布时间】:2015-09-15 23:53:45
【问题描述】:

我需要查询表才能返回行,但我无法正确查询表。这是我的表格视图:

Base    Altezza Materiale
10      10      Ferro
10      10      Legno
10      30      Ferro
10      30      Legno
10      30      Acciaio
20      20      Legno

结果集应该返回:

Base    Altezza Materiale
10      10      Ferro, Legno
10      30      Ferro, Legno, Acciaio
20      20      Legno

有人可以帮帮我吗?

【问题讨论】:

标签: sql sql-server tsql


【解决方案1】:

使用Stuff 函数和XML Path 连接你的行:

创建样本表:

create table mytable (Base int, Altezza int,  Materiale varchar(50));

insert into mytable values
(10, 10, 'Ferro'),
(10, 10, 'Legno'),
(10, 30, 'Ferro'),
(10, 30, 'Legno'),
(10, 30, 'Acciaio'),
(20, 20, 'Legno');

查询:

select distinct base,
       altezza,     
       STUFF((Select ','+ materiale
               from mytable T1
             where T1.base=T2.base
               and t1.altezza = t2.altezza
             FOR XML PATH('')),1,1,'') as Materiale
from mytable T2;

结果:

+------+---------+---------------------+
| base | altezza |      Materiale      |
+------+---------+---------------------+
|   10 |      10 | Ferro,Legno         |
|   10 |      30 | Ferro,Legno,Acciaio |
|   20 |      20 | Legno               |
+------+---------+---------------------+

SQL Fiddle Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 2012-06-17
    • 2017-07-05
    • 2021-09-12
    • 1970-01-01
    • 2012-10-20
    相关资源
    最近更新 更多