我有下面的查询工作正常,但没有按季度分组,我希望两个单行与季度数据

时间:2017-05-27 11:38:58

标签: php sql

这是我的查询

select
    a.TrustMemName,
    a.DonorFirstName,
    CASE WHEN a.DateFulfilled1 between '2017-01-01' and '2017-03-31' THEN sum(a.AmountFulfilled) 
      ELSE null
   END as qurter1,
   CASE WHEN a.DateFulfilled1 between '2017-04-01' and '2017-06-30' THEN sum(a.AmountFulfilled) 
                ELSE null
          END as qurter2,
   CASE WHEN a.DateFulfilled1 between '2017-07-01' and '2017-09-30' THEN sum(a.AmountFulfilled) 
                ELSE null
            END as quarter3,
   CASE WHEN a.DateFulfilled1 between '2017-10-01' and '2017-12-31' THEN sum(a.AmountFulfilled) 
                ELSE null
            END as quarter4

from
   commitmentcomplete as a
where a.YourCommitmentId=171
group by a.YourCommitmentId,QUARTER(a.DateFulfilled1)

--------------------输出------------------------- < / p>

TrustMemName | DonorFirstName | qurter1 | qurter2 | quarter3 | quarter4    
nithin       |   xdfcdg       |   3000  |  null   |   null   |  null    
nithin       |   xdfcdg       |   null  |  1500   |   null   |  null

这里我需要在quarter2列的第一行中有1500个,谢谢

2 个答案:

答案 0 :(得分:1)

您必须将CASE放在SUM

SUM( CASE WHEN a.DateFulfilled1 between '2017-01-01' and '2017-03-31' 
          THEN a.AmountFulfilled          
     END) as qurter1,
SUM( CASE WHEN a.DateFulfilled1 between '2017-04-01' and '2017-06-30' 
          THEN a.AmountFulfilled          
     END) as qurter2,
SUM( CASE WHEN a.DateFulfilled1 between '2017-07-01' and '2017-09-30' 
          THEN a.AmountFulfilled          
     END) as qurter3,
SUM( CASE WHEN a.DateFulfilled1 between '2017-10-01' and '2017-12-31' 
          THEN a.AmountFulfilled          
     END) as qurter4

我删除ELSE NULL,因为这是默认选项。

您只需要GROUP BY a.YourCommitmentId无需包含QUARTER()

答案 1 :(得分:0)

按照Juan的建议进行更改,并且请从group by子句中删除QUARTER(a.DateFulfilled1)。