剛逛論壇,發現一個這樣的問題,如果不建立一個新的月份的表,可以用CET來解決。給定一張表(列有月份,銷售額),要求查詢出月份、本月銷售額、上月銷售額這三個結果,如果當月上個月的銷售額不存在就顯示為“*”。if exists (select * from sysobjects where id = o...
剛逛論壇,發現一個這樣的問題,如果不建立一個新的月份的表,可以用CET來解決。
給定一張表(列有月份,銷售額),要求查詢出月份、本月銷售額、上月銷售額這三個結果,如果當月上個月的銷售額不存在就顯示為“*”。
if exists (select * from sysobjects where id = object_id(N'[tb2]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [tb2] CREATE TABLE tb2( ID INT IDENTITY, SALEDATE DATETIME, AMOUNT FLOAT ) INSERT INTO tb2 SELECT '2015-05-02',20.1 INSERT INTO tb2 SELECT '2015-02-02',24.1 INSERT INTO tb2 SELECT '2015-03-02',10.4 INSERT INTO tb2 SELECT '2015-05-12',27.8 INSERT INTO tb2 SELECT '2015-06-02',70.13 INSERT INTO tb2 SELECT '2015-06-12',90.31 INSERT INTO tb2 SELECT '2016-01-06',30.22 INSERT INTO tb2 SELECT '2016-02-08',5.7
插入後顯示表的數據
SELECT * FROM tb2
用以下sql跑出所需要的結果
WITH MON as( select CONVERT(VARCHAR(7),GETDATE(),120) AS MO UNION SELECT CONVERT(VARCHAR(7),DATEADD(M,-1,GETDATE()),120) AS MO ) SELECT MO AS MONTH,CASE WHEN SUM(ISNULL(AMOUNT,0))=0 THEN '*' ELSE CAST(SUM(ISNULL(AMOUNT,0)) AS VARCHAR(10)) END AS SUM_AMOUNT FROM Mon LEFT JOIN tb2 ON MO=CONVERT(VARCHAR(7),SALEDATE,120) GROUP BY MO
如果還有其他好的方法,希望互相交流下,謝謝!