您好,登錄后才能下訂單哦!
本篇文章為大家展示了如何使用sqlserver統(tǒng)計(jì)全天各個(gè)時(shí)間段產(chǎn)品銷量情況,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
現(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ù)可以通過系統(tǒng)的數(shù)字輔助表
spt_values來實(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
來看一下最終效果,只有1天的數(shù)據(jù),可能看起來不是很直觀。
本文的技術(shù)點(diǎn)有2個(gè):
1.利用數(shù)字輔助表補(bǔ)全缺失的記錄
2.pivot行轉(zhuǎn)列函數(shù)的使用
上述內(nèi)容就是如何使用sqlserver統(tǒng)計(jì)全天各個(gè)時(shí)間段產(chǎn)品銷量情況,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。