按月和月生成统计数据

时间:2016-02-04 06:50:30

标签: mysql sql

上次我使用间隔,但我认为它不像我想的那样工作,  我只是想申报年月......任何大师都可以在这里教我?

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里面做清关报告吗?

2 个答案:

答案 0 :(得分: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' )

答案 1 :(得分:-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]