SQL查询,用于生成一年中每个月的计数

时间:2016-08-16 22:18:45

标签: mysql sql-server

我需要为一年中的每个月生成一个交易计数。我有以下查询:

select state, taxing_entity, count(taxing_entity)Total_TRXN_Count
from taxes where effect_date between '2015/01/01' and '2015/12/31' 
group by state, taxing_entity, effect_date

我尝试了各种方法,例如GROUP BY YEAR(record_date), MONTH(record_date)GROUP BY DATE_FORMAT(record_date, '%Y%m')。如何更改上述查询以便生成一年中每个月的交易计数,而无需在结束时手动更改年份

3 个答案:

答案 0 :(得分:2)

select MONTH(effect_date) Reporting_Month
     , state
     , taxing_entity
     , count(taxing_entity) Total_TRXN_Count
  from taxes 
 where effect_date between '2015/01/01' and '2015/12/31' 
 group by MONTH(effect_date)
     , state
     , taxing_entity
 order by MONTH(effect_date)
     , state
     , taxing_entity

这样做你想要的吗?它应该按月为每个州和taxing_entity提供总计。

答案 1 :(得分:0)

select state, taxing_entity, 
       YEAR(effect_date), MONTH(effect_date),
       count(taxing_entity) AS Total_TRXN_Count
from  taxes 
where effect_date between '2015/01/01' and '2015/12/31' 
group by state, taxing_entity, YEAR(effect_date), MONTH(effect_date)

答案 2 :(得分:0)

您不需要WHERE子句,因为聚合会自动按年分隔数据:

SELECT state
     , taxing_entity
     , DATE_FORMAT(record_date, '%Y-%m') YearMonth
     , COUNT(taxing_entity) AS Total_TRXN_Count
  FROM taxes 
 GROUP BY state
        , taxing_entity
        , DATE_FORMAT(record_date, '%Y-%m')
;

我选择按DATE_FORMAT(record_date, '%Y-%m')汇总。

如果您愿意,还可以按年份和月份在单独的列中进行汇总:YEAR(record_date), MONTH(record_date)

如果要将数据导入Microsoft Excel,我建议"截断"到该月的第一天的日期,然后在Excel中更改格式以仅显示月份和年份: DATE_FORMAT(record_date, '%Y-%m-01')