请问任何人如何在sql中编写以下scenerio的代码。
(ol
(li :text "first")
(li :text "second"))
这里:第1个月= 1月,2 =非常,3 = 3月
输出是特定DECLARE @T TABLE
(
Year VARCHAR (50),
Month VARCHAR (50),
GROUPS VARCHAR (50),
SALESPERNO VARCHAR (50),
Net VARCHAR (50)
)
INSERT @T
SELECT '2014','1','A','6607','109.34' UNION ALL
SELECT '2014','2','A','6607','13.42' UNION ALL
SELECT '2014','3','A', '6607','359.41' UNION ALL
SELECT '2014','1','A', '6608','99.52' UNION ALL
SELECT '2014','2','A','6608','95.62' UNION ALL
SELECT '2014','3','A', '6608','89.63' UNION ALL
SELECT '2014','1','B','8888','340.95' UNION ALL
SELECT '2014','2','B','8888','652.25' UNION ALL
SELECT '2014','3','B','8888','352.26'
SELECT * FROM @T
的净值与jan feb mar和total的总和,如下所示:
salesperno
答案 0 :(得分:0)
您可以通过多种方式执行此操作。正如Tab Alleman建议的一种方法是在CASE和GROUP BY的帮助下。
select
SUM(CASE WHEN [Month]=1 THEN [NET] END) [January],
SUM(CASE WHEN [Month]=2 THEN [NET] END) [February],
SUM(CASE WHEN [Month]=3 THEN [NET] END) [March],
SUM([NET]) [QFY],
[GROUPS] [SALES_GROUP],
[SALESPERNO] [SALESPERSON_NUMBER]
from @T
group by
[GROUPS],
[SALESPERNO]
这是另一种方式,PIVOT
SELECT
[1] [January],
[2] [February],
[3] [March],
[1]+[2]+[3] [QFY],
[GROUPS] [SALES_GROUP],
[SALESPERNO] [SALESPERSON_NUMBER]
FROM @T
PIVOT (
SUM(NET)
FOR [Month] in ([1],[2],[3])
) pvt