小计 合计 -统计
create?table?[tb]([客戶編碼]?varchar(10),[客戶名稱]?varchar(10),[數量]?int)
insert?[tb]
select?'001','A',2?union?all
select?'001','A',3?union?all
select?'001','A',4?union?all
select?'002','B',1?union?all
select?'002','B',2
--統計
select?*?from
(select?*?from tb
?union?all?
?select 客戶編碼 , 客戶名稱 =?'小計' , sum(數量) 數量 from tb group?by 客戶編碼
?union?all
?select 客戶編碼 =?'', 客戶名稱 =?'合計' , sum(數量) 數量 from tb
) t
order?by??
case 客戶編碼 when?''?then?2?else?1?end ,客戶編碼 ,
case 客戶名稱 when?'小計'?then?2?else?1?end???
drop?table tb
/*
客戶編碼?????? 客戶名稱?????? 數量??????????
---------- ---------- -----------?
? 001????????????? A?????????????? 2
? 001????????????? A?????????????? 3
? 001????????????? A?????????????? 4
? 001???????????? 小計?????????? 9
? 002????????????? B?????????????? 1
? 002????????????? B?????????????? 2
? 002???????????? 小計?????????? 3
???????????????? 合計?????????? 12
(所影響的行數為 8 行)
*/
?
?
?
?
?
?
create table tb (date char(10),col varchar(10))
insert tb select '2005-05-09','勝'
insert tb select '2005-05-09','勝'
insert tb select '2005-05-09','負'
insert tb select '2005-05-09','負'
insert tb select '2005-05-10','勝'
insert tb select '2005-05-10','負'
insert tb select '2005-05-10','負'
select date
,sum(case when col='勝' then 1 else 0 end) as [勝]
,sum(case when col='負' then 1 else 0 end) as 負
from tb
group by date
date?????? 勝?????????? 負
---------- ----------- -----------
2005-05-09 2?????????? 2
2005-05-10 1?????????? 2
(2 行受影響)
?
轉載于:https://www.cnblogs.com/zengxiangzhan/archive/2010/01/03/1638155.html
總結