带有月份名称列的区间统计信息

时间:2016-02-08 16:16:39

标签: mysql sql sql-server-2008

上次我使用间隔,但我认为它不像我想的那样工作,  我只想宣布年月。任何宗师都可以在这教我吗?

这是样本数据作为请求:

food_type | sales | date_sales
   pizza     buy     02-01-2015 12:00:00
   pizza     buy     02-01-2015 03:00:00
   pizza     sell     03-01-2015 01:00:00
   pizza     sell     04-01-2015 05:00:00
   pizza     buy     05-01-2015 02:00:00

这是我想要的样本

DECLARE @Startdate AS datetime = '02-01-2015',
 @Enddate AS datetime = '05-01-2015'


SELECT TYPE_FOOD, COUNT(CASE WHEN STATUS = 'BUY' THEN 1 END) AS [INCOMING], COUNT(CASE WHEN STATUS= 'SELL' THEN 1 END) AS [OUTGOING]
FROM Shop WHERE [Something_Date] BETWEEN @StartDate AND @EndDate

OR

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 )

- 我不能使用datediff,因为我想在约会之间..

如果使用datediff,我可以获得最接近的查询...不再仅仅是一年......

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

如何制作这样的sql输出:

Food TYPE | MONTH   |   BUY | SELL | 
 pizza       Feb-15     10    5        
 pizza       Mar-15     3     1       
 ....        ...       ..     ..     
 pizza       May-15     5     2   

请帮助我大师,我仍然是sql的初学者

1 个答案:

答案 0 :(得分:0)

我认为你需要一个总和一个由type_food

 select TYPE_FOOD, date_format(date_sales, '%m -  %Y'),
 sum(case when sales = 'buy' then 1 else 0 end) as incoming,
 sum(case when sales = 'sell' then 1 else 0 end) as outgoing
 from shop
 group by type_food