數據庫環境:SQL SERVER 2005
現有一個產品銷售實時表,表數據如下:
字段name是產品名稱,字段type是銷售類型,1表示售出,2表示退貨,字段num是數量,字段ctime是操作時間。
要求:
在一行中統計24小時內所有貨物的銷售(售出,退貨)數據,把日期考慮在內。
分析:
這實際上是行轉列的一個應用,在進行行轉列之前,需要補全24小時的所有數據。補全數據可以通過系統的數字輔助表
spt_values來實現,進行行轉列時,根據type和處理後的ctime分組即可。
1.建表,導入數據
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.補全24小時的數據
/*枚舉0-23自然數列*/ 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 ),/*補全所有日期的24小時*/ 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 ),/*整理行轉列需要用到的數據*/ x4 AS ( SELECT x2.d , x2.h , x3.name , x3.type , x3.num FROM x2 LEFT JOIN x3 ON x3.h = x2.h )
3.行轉列
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天的數據,可能看起來不是很直觀。
本文的技術點有2個:
1.利用數字輔助表補全缺失的記錄
2.pivot行轉列函數的使用
以上內容是如何統計全天各個時間段產品銷量情況(sqlserver)的全部內容,希望大家喜歡。