1. 統計各個條件下的數據post
select BatchId,sum(CardSum) 總金額, sum(case when Status=1 then CardSum else 0 end) as 已使用, sum(case when Status=2 then CardSum else 0 end) as 已凍結 from GiftCard group by BatchId
2. 統計每日,每個月,每一年的數據測試
select year(AddTime) 年,month(AddTime) 月,day(AddTime) 日,COUNT(1) 數量,sum(CardSum) 銷售合計 from GiftCard group by year(AddTime),month(AddTime),day(AddTime)
3. 某列去重統計code
select COUNT(BatchId),COUNT(distinct BatchId),COUNT(distinct BatchName) from GiftCard
4. 行轉列blog
SELECT * FROM ( SELECT BatchName, CardSum as TotAmount FROM GiftCard ) as s PIVOT ( SUM(TotAmount) FOR BatchName IN (zx測試商品, test新人優惠券,測試高考大放送) )AS MyPivot
5. 獲得表中最小的未使用的ID號it
SELECT (CASE WHEN EXISTS(SELECT * FROM GiftCard b WHERE b.Id = 1) THEN MIN(Id) + 1 ELSE 1 END) as Id FROM GiftCard WHERE NOT Id IN (SELECT a.Id - 1 FROM GiftCard a)
6. 查詢某一列數據不重複的數量class
select *
from GiftCard a
where not exists(select 1 from GiftCard where BatchName=a.BatchName and ID<a.ID)
7. 按年統計1月到12個月的銷量test
select year(AddTime) as '年', SUM(case when MONTH(AddTime)=1 then CardSum else 0 end ) as '一月', SUM(case when MONTH(AddTime)=2 then CardSum else 0 end ) as '二月', SUM(case when MONTH(AddTime)=3 then CardSum else 0 end ) as '三月', SUM(case when MONTH(AddTime)=4 then CardSum else 0 end ) as '四月', SUM(case when MONTH(AddTime)=5 then CardSum else 0 end ) as '五月', SUM(case when MONTH(AddTime)=6 then CardSum else 0 end ) as '六月', SUM(case when MONTH(AddTime)=7 then CardSum else 0 end ) as '七月', SUM(case when MONTH(AddTime)=8 then CardSum else 0 end ) as '八月', SUM(case when MONTH(AddTime)=9 then CardSum else 0 end ) as '九月', SUM(case when MONTH(AddTime)=10 then CardSum else 0 end ) as '十月', SUM(case when MONTH(AddTime)=11 then CardSum else 0 end ) as '十一月', SUM(case when MONTH(AddTime)=12 then CardSum else 0 end ) as '十二月' from GiftCard group by year(AddTime)