數(shù)據(jù)庫(kù)環(huán)境:SQL SERVER 2005
現(xiàn)有一個(gè)產(chǎn)品銷售實(shí)時(shí)表,表數(shù)據(jù)如下:
字段name是產(chǎn)品名稱,字段type是銷售類型,1表示售出,2表示退貨,字段num是數(shù)量,字段ctime是操作時(shí)間。
要求:
在一行中統(tǒng)計(jì)24小時(shí)內(nèi)所有貨物的銷售(售出,退貨)數(shù)據(jù),把日期考慮在內(nèi)。
分析:
這實(shí)際上是行轉(zhuǎn)列的一個(gè)應(yīng)用,在進(jìn)行行轉(zhuǎn)列之前,需要補(bǔ)全24小時(shí)的所有數(shù)據(jù)。補(bǔ)全數(shù)據(jù)可以通過(guò)系統(tǒng)的數(shù)字輔助表
spt_values來(lái)實(shí)現(xiàn),進(jìn)行行轉(zhuǎn)列時(shí),根據(jù)type和處理后的ctime分組即可。
1.建表,導(dǎo)入數(shù)據(jù)
CREATE TABLE snake (name VARCHAR(10 ),type INT,num INT, ctime DATETIME )
INSERT INTO snake VALUES(' 方便面', 1,10 ,'2015-08-10 16:20:05')
INSERT INTO snake VALUES(' 香煙A ', 2,2 ,'2015-08-10 18:21:10')
INSERT INTO snake VALUES(' 香煙A ', 1,5 ,'2015-08-10 20:21:10')
INSERT INTO snake VALUES(' 香煙B', 1,6 ,'2015-08-10 20:21:10')
INSERT INTO snake VALUES(' 香煙B', 2,9 ,'2015-08-10 20:21:10')
INSERT INTO snake VALUES(' 香煙C', 2,9 ,'2015-08-10 20:21:10')
2.補(bǔ)全24小時(shí)的數(shù)據(jù)
/*枚舉0-23自然數(shù)列*/
WITH x0
AS ( SELECT number AS h
FROM master..spt_values
WHERE type = 'P'
AND number >= 0
AND number = 23
),/*找出表所有的日期*/
x1
AS ( SELECT DISTINCT
CONVERT(VARCHAR(100), ctime, 23) AS d
FROM snake
),/*補(bǔ)全所有日期的24小時(shí)*/
x2
AS ( SELECT x1.d ,
x0.h
FROM x1
CROSS JOIN x0
),
x3
AS ( SELECT name ,
type ,
num ,
DATEPART(hour, ctime) AS h
FROM snake
),/*整理行轉(zhuǎn)列需要用到的數(shù)據(jù)*/
x4
AS ( SELECT x2.d ,
x2.h ,
x3.name ,
x3.type ,
x3.num
FROM x2
LEFT JOIN x3 ON x3.h = x2.h
)
3.行轉(zhuǎn)列
SELECT ISNULL([0], 0) AS [00] ,
ISNULL([1], 0) AS [01] ,
ISNULL([2], 0) AS [02] ,
ISNULL([3], 0) AS [03] ,
ISNULL([4], 0) AS [04] ,
ISNULL([5], 0) AS [05] ,
ISNULL([6], 0) AS [06] ,
ISNULL([3], 7) AS [07] ,
ISNULL([8], 0) AS [08] ,
ISNULL([9], 0) AS [09] ,
ISNULL([10], 0) AS [10] ,
ISNULL([3], 11) AS [11] ,
ISNULL([12], 0) AS [12] ,
ISNULL([13], 0) AS [13] ,
ISNULL([14], 0) AS [14] ,
ISNULL([3], 15) AS [15] ,
ISNULL([16], 0) AS [16] ,
ISNULL([17], 0) AS [17] ,
ISNULL([18], 0) AS [18] ,
ISNULL([19], 15) AS [19] ,
ISNULL([20], 0) AS [20] ,
ISNULL([21], 0) AS [21] ,
ISNULL([22], 0) AS [22] ,
ISNULL([23], 15) AS [23] ,
type ,
d AS date
FROM ( SELECT d ,
h ,
type ,
num
FROM x4
) t PIVOT( SUM(num) FOR h IN ( [0], [1], [2], [3], [4], [5], [6],
[7], [8], [9], [10], [11], [12],
[13], [14], [15], [16], [17], [18],
[19], [20], [21], [22], [23] ) ) t
WHERE type IS NOT NULL
來(lái)看一下最終效果,只有1天的數(shù)據(jù),可能看起來(lái)不是很直觀。
本文的技術(shù)點(diǎn)有2個(gè):
1.利用數(shù)字輔助表補(bǔ)全缺失的記錄
2.pivot行轉(zhuǎn)列函數(shù)的使用
以上內(nèi)容是如何統(tǒng)計(jì)全天各個(gè)時(shí)間段產(chǎn)品銷量情況(sqlserver)的全部?jī)?nèi)容,希望大家喜歡。
您可能感興趣的文章:- SQLserver 實(shí)現(xiàn)分組統(tǒng)計(jì)查詢(按月、小時(shí)分組)
- SQLServer2005 中的幾個(gè)統(tǒng)計(jì)技巧
- sqlserver 統(tǒng)計(jì)sql語(yǔ)句大全收藏
- SQLSERVER收集語(yǔ)句運(yùn)行的統(tǒng)計(jì)信息并進(jìn)行分析
- SQLSERVER語(yǔ)句的執(zhí)行時(shí)間顯示的統(tǒng)計(jì)結(jié)果是什么意思