SQL查询计算每月一列中的值的数量

时间:2017-05-18 04:16:48

标签: sql sql-server sql-server-2008 stored-procedures

id   date          sales  req      arivve
1    01/01/2015    100    accept   deny
2    01/01/2015    100    deny     deny
3    02/01/2015    100    accept   accept
4    03/01/2015    100    accept   deny

我需要的是计算接受'每月req和arrival列的值。这是预期的输出

Month  StartMonth  EndMonth     TotalSales reqCount  arriveAcount
1      01/01/2015  01/31/2015   200        1         0
2      02/01/2015  02/28/2015   100        1         1
3      03/01/2015  03/31/2015   100        1         0
4      04/01/2015  04/30/2015   0          0         0

这就是我已经拥有的(开始和结束年份的输入由用户提供,因此月份切线是动态的)

--step 1
select id, date, capacity, sales, req, arrive
into #First
from Sales
where date between @StartDate and @EndDate;


--step 2 b
WITH cte
    AS
    (SELECT
          FORMAT(MONTH([schedule_date]), '0#')
        + '-' + CONVERT(VARCHAR(20), YEAR([schedule_date])) monthyear 
        ,([capacity]), request_status, arrival_status
    FROM #First)


    SELECT
    (SELECT DATEADD(MONTH, SUBSTRING(monthyear, 1, 2) - 1, DATEADD(YEAR, SUBSTRING(monthyear, 4, 4) - 1900, 0)))    StartDate
    ,(SELECT DATEADD(DAY, -1, DATEADD(MONTH, CAST(SUBSTRING(monthyear, 1, 2) AS INT), DATEADD(YEAR, SUBSTRING(monthyear, 4, 4) - 1900, 0)))) EndDate
    ,SUM(capacity) totalsales   

    FROM cte
    GROUP BY monthyear

1 个答案:

答案 0 :(得分:1)

尝试:

select DATEPART(month, date)
, date as StartMonth
, dateadd(day, -1 , DATEADD(month, 1, date))
, sum(sales)
, sum(case when req = 'accept' then 1 else 0 end) reqCount
, sum(case when arivve = 'accept' then 1 else 0 end) arriveCount
from mytable
group by date