请帮助我 mssql问题。 我有一些表结构:
Category amt year month
cat1 800.00 2013 jan
cat2 30.00 2013 jan
cat3 120.00 2013 feb
cat4 125.00 2013 feb
我希望数据来源(逐月)示例...
Month cat1 cat2 cat3 cat4
jan 800.00 30.00 0.00 0.00
feb 0.00 0.00 120.00 125.00
答案 0 :(得分:1)
您可以使用PIVOT。请检查查询:
SELECT
[Month],
isnull(cat1, 0.00) cat1,
isnull(cat2, 0.00) cat2,
isnull(cat3, 0.00) cat3,
isnull(cat4, 0.00) cat4
FROM(
SELECT 'cat1' Category, 800.00 amt,2013 [year], 'jan' [month] UNION
SELECT 'cat2' Category, 30.00 amt, 2013 [year], 'jan' [month] UNION
SELECT 'cat3' Category, 120.00 amt, 2013 [year], 'feb' [month] UNION
SELECT 'cat4' Category, 125.00 amt, 2013 [year], 'feb' [month]
)UP
PIVOT (SUM(amt) FOR Category IN (cat1, cat2, cat3, cat4)) AS PVT
答案 1 :(得分:1)
如果我理解正确,您希望在交叉表中获取数据?如果是这种情况,您可以使用数据透视表。
select
month
, coalesce(cat1,0) as cat1
, coalesce(cat2,0) as cat2
, coalesce(cat3,0) as cat3
, coalesce(cat4,0) as cat4
from tbl
pivot(sum(amt) for category in ([cat1], [cat2], [cat3], [cat4])) p