34,696
社区成员
发帖
与我相关
我的任务
分享
如表#t1,数据如下:
我想让code相同时,实现小计,最后是总计,数据变成如下图:
如何写sql语句实现?写这个SQL语句能在sqlserver2012运行。
--示例数据
SELECT * INTO #temp FROM (
SELECT 'A1001' AS code , '2024-8-1' AS listdate ,'' AS custname , 20 AS quantity UNION
SELECT 'A1003' , '2024-8-9' ,'广州客户' , 40 UNION
SELECT 'A1005' , '2024-8-3' ,'佛山客户' , 50 UNION
SELECT 'A1001' , '2024-8-2' ,'佛山客户' , 60 UNION
SELECT 'A1005' , '2024-8-4' ,'' , 30 ) a
--最终输出
SELECT * FROM (
SELECT code,listdate,custname,quantity FROM (
SELECT code,listdate,custname,quantity
FROM #temp
UNION
SELECT code+'小计','','',SUM(quantity)
FROM #temp
GROUP BY code) t
UNION ALL
SELECT '总计','','',SUM(quantity) FROM
(SELECT code,listdate,custname,quantity
FROM #temp
UNION
SELECT code+'小计','','',SUM(quantity)
FROM #temp
GROUP BY code) p
WHERE CHARINDEX('小计',code)>0) m
ORDER BY code