我有一张看起来像这样的表
ID | Value | Type
-----------------------
1 | 50 | Travel
1 | 25 | Non-Travel
1 | 25 | Non-Travel
1 | 25 | Non-Travel
1 | 50 | Travel
1 | 75 | Non-Travel
如何查询以使输出重新排列?
ID | Travel | Non-Travel
------------------------
1 | 100 | 150
实际获取我发布的第一个表的查询在其中一个表中有许多连接和一个BIT列,其中0或NULL是非旅行,1是旅行。所以我有这样的事情:
SELECT
[ID]
,CASE WHEN [IsTravel] IN (0,NULL) THEN ISNULL(SUM([VALUE]),0) END AS 'NonTravel'
,CASE WHEN [IsTravel] = 1 THEN ISNULL(SUM([VALUE]),0) END AS 'Travel'
FROM
...
然而,结果最终显示了这个
ID | Travel | Non-Travel
------------------------
1 | 100 | NULL
1 | NULL | 150
如何编辑查询以合并行以显示此结果?
ID | Travel | Non-Travel
------------------------
1 | 100 | 150
提前致谢。
答案 0 :(得分:1)
您需要将每个条件包装在聚合中,例如MAX()
和GROUP BY
其他列,以汇总值并移除NULL
。像这样:
SELECT
[ID]
,MAX(CASE WHEN [IsTravel] IN (0,NULL) THEN ISNULL(SUM([VALUE]),0) END) AS 'NonTravel'
,MAX(CASE WHEN [IsTravel] = 1 THEN ISNULL(SUM([VALUE]),0) END) AS 'Travel'
FROM
...
GROUP BY [ID]
如果逻辑过于混乱或混乱(在不查看整个当前查询的情况下不知道),请将这些结果放入临时表或CTE并执行简单的MAX()
和GROUP BY
从那里。
答案 1 :(得分:1)
您可以使用以下角色:
Select * from (
Select Id, [Value], [Type] from yourtable ) a
pivot (sum([Value]) for [Type] in ([Travel],[Non-Travel]) ) p
输出如下:
+----+------------+--------+
| Id | Non-Travel | Travel |
+----+------------+--------+
| 1 | 150 | 100 |
+----+------------+--------+
对于旅行类型的动态列表,您可以执行以下动态查询:
Declare @cols1 varchar(max)
Declare @query nvarchar(max)
Select @cols1 = stuff((select Distinct ','+QuoteName([Type]) from #traveldata for xml path('')),1,1,'')
Set @query = ' Select * from (
Select Id, [Value], [Type] from #traveldata ) a
pivot (sum([Value]) for [Type] in (' + @cols1 + ') ) p '
Exec sp_executesql @query
答案 2 :(得分:1)
select ID,
SUM(CASE WHEN Type = 'Travel' THEn value ELSE 0 END) [Travel],
SUM(CASE WHEN Type = 'NonTravel' THEn value ELSE 0 END) [NonTravel]
from @Table1
GROUP BY ID