SQL - 如何将结果汇总到1行

时间:2016-10-24 15:48:56

标签: tsql

如果我有桌子:

ID NAME 
1  Red 
2  Blue 
3  Green

如何返回查询以便我的结果为:

Col1  Col2   Col3
Red   Blue   Green

我会自己进行内部联接还是需要数​​据透视表?

2 个答案:

答案 0 :(得分:1)

是的,您可以通过加入来完成,例如:

select t1.name col1, t2.name col2, t3.name col3
from yourtable t1
join yourtable t2 on t2.id=2 
join yourtable t3 on t3.id=3 
where t1.id=1;

或者您可以使用嵌入式选择语句来执行此操作,例如: 在MySQL中:

select
  (select name from yourtable where id=1) col1, 
  (select name from yourtable where id=2) col2,
  (select name from yourtable where id=3) col3;

在Oracle中:

select
  (select name from yourtable where id=1) col1, 
  (select name from yourtable where id=2) col2,
  (select name from yourtable where id=3) col3
from dual;

当然,在该查询中,cols的数量是固定的,如果添加更多行以进行汇总,则必须对其进行编辑。

答案 1 :(得分:0)

您可以将动态SQL与PIVOT一起使用:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' +     QUOTENAME(id) 
                from yourtable
                group by ColumnName, id
                order by id
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

set @query = N'SELECT ' + @cols + N' from 
         (
            select id, ColumnName
            from yourtable
        ) x
        pivot 
        (
            max(ColumnName)
            for id in (' + @cols + N')
        ) p '

exec sp_executesql @query;