詳解MySQL中ALTER敕令的應用。本站提示廣大學習愛好者:(詳解MySQL中ALTER敕令的應用)文章只能為提供參考,不一定能成為您想要的結果。以下是詳解MySQL中ALTER敕令的應用正文
數據庫情況: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)的全體內容,願望年夜家愛好。