2016-02-04 94 views
2

上次我使用時間間隔,但我不認爲它像我想要的那樣工作, 我只是想聲明年份和月份..任何大師都可以教我這裏嗎?按月份和月份生成統計信息

DECLARE @YEAR AS INT = '2015', 
@MONTH AS INT = '1', 
    @YEARTO AS INT = '2015', 
    @MONTHTO AS INT = '1' 


SELECT TYPE_FOOD, COUNT(CASE WHEN STATUS = 'BUY' THEN 1 END) AS [INCOMING], COUNT(CASE WHEN STATUS= 'SELL' THEN 1 END) AS [OUTGOING],DATEDIFF(MONTH, DATE_OF_PURCHASE, @YEAR) AS [YEAR] 
FROM Shop 
GROUP BY TYPE_FOOD, DATEDIFF(MONTH,DATE_OF_PURCHASE, @YEAR) 

我當前的查詢..

Food TYPE | MONTH | BUY | SELL 
pizza  12  10  5  
pizza  13  3  1  
....  ...  ..  ..  
pizza  32  5  2   

如何使這樣的SQL:

Food TYPE | MONTH | BUY | SELL | CLEARANCE RATE % 
pizza  Jan-15  10 5  50% 
pizza  Feb-15  3  1  25% 
....  ...  ..  ..  .. 
pizza  Dec-15  5  2  35% 

,我可以做的間隙內報告SQL嗎?

回答

-1

試試這個:

SELECT TYPE_FOOD, COUNT(CASE WHEN STATUS = 'BUY' THEN 1 END) AS [BUY], 
COUNT(CASE WHEN STATUS= 'SELL' THEN 1 END) AS [SELL], 
MONTHNAME(DATE_OF_PURCHASE) AS [MONTH], 
[INCOMING]*100/[OUTGOING] AS [CLEARANCE RATE %] 
FROM Shop 
GROUP BY TYPE_FOOD, [MONTH] 
+0

這是斯巴達,又名myswl,而不是MS SQL。您的解決方案會產生語法錯誤。 – Shadow

+0

它表示沒有傳入和傳出表 – JohhnyNewbie

+0

Mysql以及sql中提到的問題標記 –

0

使用DATE_FORMAT()函數來獲取月份和年份從購買的列日期:

SELECT TYPE_FOOD, COUNT(CASE WHEN STATUS = 'BUY' THEN 1 END) AS INCOMING, COUNT(CASE WHEN STATUS= 'SELL' THEN 1 END) AS OUTGOING,DATE_FORMAT(DATE_OF_PURCHASE, '%b-%Y') AS YEAR, COUNT(CASE WHEN STATUS = 'BUY' THEN 1 END) * 100/COUNT(CASE WHEN STATUS= 'SELL' THEN 1 END) AS clearance_rate 
FROM Shop 
GROUP BY TYPE_FOOD, DATE_FORMAT(DATE_OF_PURCHASE,'%b-%Y')