【发布时间】:2014-05-06 04:06:22
【问题描述】:
我无法通过 SQL 查询获得所需的输出。
我的sql数据如下:
TOTAL Charge PAYMNET A B C D E MonthYear
------- ----------- ----------- --------- -------- ---------- ------- ------- ----------
661 157832.24 82967.80 700.00 10.70 58329.33 0.00 0.00 Oct-2013
612 95030.52 17824.28 850.00 66.10 53971.41 0.00 0.00 Nov-2013
584 90256.35 16732.91 700.00 66.10 52219.87 0.00 0.00 Dec-2013
511 72217.32 12336.12 285.00 53.17 42951.12 0.00 0.00 Jan-2014
我需要输出如下,
Data Jan-2013 Feb-2013 Mar-2013
TOTALCOUNT 761 647 671
Charge 126888 119995 151737.5
Payment 25705.4 26235.47 28704.41
A 1089.08 1020 745
B 2100.4 1947.25 1868.22
C 94246.55 84202.15 115673.7
D 0 0 0
E 0 0 0
我已经看到pivot 和unpivot 的示例,在pivot 我没有将列标题作为行数据,在unpivot 我没有找到可以转置多个的示例列。我有另一个选择可以在代码中得到这个结果。但是我想知道在sql中是否可以得到这种结果?
编辑
结果只会给出3或4个月,不会超过那个。
更新:第一个示例数据是我将通过多个连接和对多个表进行分组而获得的实际数据,我将其存储到临时表中。我试图通过修改由于表结构而不可能的查询来获得所需的结果。我设法得到了第一个示例数据中的结果,但这不是客户想要看到的!!!所以我需要将只有 3 到 4 行的临时表数据处理成所需的输出。获得第一个结果的查询是select * from temp。需要对temp表结果进行处理。
Update-2
我尝试了以下查询
declare @cols varchar(max)
select @cols = STUFF((select ', ' + MonthYear
from #tmp for xml path('')),1,1,'')
declare @query varchar(max)
set @query =
'select ''TOTAL'' as Data,' +@cols+' from
(select MonthYear,TOTALCLAIMS from #tmp)st
pivot
(
MAX(TOTAL) for MonthYear in (' + @cols + ')
)pt;'
这给了我正确的第一行!!!但我尝试使用union as
set @query =
'select ''TOTAL'' as Data,' +@cols+' from
(select MonthYear,TOTALCLAIMS from #tmp)st
pivot
(
MAX(TOTAL) for MonthYear in (' + @cols + ')
)pt;
union
select ''CHARGES'' as Data,' +@cols+' from
(select MonthYear,TOTALCLAIMS from #tmp)st
pivot
(
MAX(CHARGES) for MonthYear in (' + @cols + ')
)pt;'
这给出了incorrect syntax near union 的错误。有人知道如何合并pivot 结果吗?或者有没有更好的方法来做到这一点?
谢谢。
【问题讨论】:
-
同一个monthyear会有多条记录吗?如果是,那么应该如何处理它们?请说明。
-
@samar 不。我不会在同一年和同一年有多个记录。
-
这可能会有所帮助,但它不是微不足道的stackoverflow.com/questions/18023479/…
-
另一种方法是循环遍历表并创建所需的表。但这并不容易,无论是在编码方面还是在性能方面。
-
去掉每个并集前的分号
标签: sql sql-server sql-server-2008 unpivot