常用的資料統計Sql 總結

2021-07-16 02:34:42 字數 2307 閱讀 9495

1. 統計各個條件下的資料

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. 某列去重統計

select count(batchid),count(distinct batchid),count(distinct batchname)

from giftcard

4. 行轉列

select *

from (

select

batchname,

cardsum as totamount

from giftcard

) as s

pivot

(

sum(totamount)

for batchname in (zx測試商品, test新人優惠券,測試高考大放送)

)as mypivot

5. 得到表中最小的未使用的id號

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. 查詢某一列資料不重複的數量

select * 

from giftcard a

where not exists(select 1 from giftcard where batchname=a.batchname and id7. 按年統計1月到12個月的銷量

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)

常用的資料統計Sql 總結

最近剛在搞乙個bi的專案,裡面需要大量的sql 資料統計相關運用,加深了我又對sql的理解與使用。所以,分享幾個資料統計時常用的sql 語句總結 1.統計各個條件下的資料 select batchid,sum cardsum 總金額,sum case when status 1 then cards...

常用的資料統計Sql 總結

最近剛在搞乙個bi的專案,裡面需要大量的sql 資料統計相關運用,加深了我又對sql的理解與使用。所以,分享幾個資料統計時常用的sql 語句總結 1.統計各個條件下的資料 select batchid,sum cardsum 總金額,sum case when status 1 then cards...

常用的資料統計Sql 總結

最近剛在搞乙個bi的專案,裡面需要大量的sql 資料統計相關運用,加深了我又對sql的理解與使用。所以,分享幾個資料統計時常用的sql 語句總結 1.統計各個條件下的資料 select batchid,sum cardsum 總金額,sum case when status 1 then cards...