Commonly used data statistics Sql summary

Recently, I was working on a BI project, which required a lot of SQL data statistics related applications, which deepened my understanding and use of SQL.



Therefore, a summary of some commonly used sql statements in data statistics:



1. Statistical data under various conditions

select
BatchId, sum(CardSum) total amount,
sum(case when Status=1 then CardSum else 0 end) as used,
sum (case when Status=2 then CardSum else 0 end) as Frozen
from GiftCard
group by BatchId



2. Count daily, monthly, annual data

select year(AddTime) year, month(AddTime) month, day(AddTime) day ,COUNT(1) Quantity,sum(CardSum) Total sales
from GiftCard
group by year(AddTime),month(AddTime),day(AddTime)



3.

Select COUNT(BatchId),COUNT(distinct BatchId), COUNT(distinct BatchName)
from GiftCard



4. Row to Column


Copy code
SELECT *
FROM (
    SELECT
        BatchName,
        CardSum as TotAmount
    FROM GiftCard

) as s
PIVOT
(   
    SUM(TotAmount)
    FOR BatchName IN (zx test product, test newcomer coupon, test college entrance examination big release)
) AS MyPivot

copy code



5. Get the smallest unused ID in the table No.

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 . Query the number of unique data in a column

select *
from GiftCard a
where not exists(select 1 from GiftCard where BatchName=a.BatchName and ID<a.ID) 7.




Count sales from January to 12 months by year select year(AddTime) as 'year',




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 'November',
SUM(case when MONTH(AddTime)=12 then CardSum else 0 end ) as 'December'

from GiftCard

group by year (AddTime)

Author: Zhang Weizhong
Source : http://www.cnblogs.com/zhangweizhong/

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326781817&siteId=291194637