1

我有一个按字段描述分组的查询。(总共有 9 个描述。)我需要以某种方式将其中的 3 个描述组合成一组,总共有 7 个描述。我是 sql 查询的新手,所以到目前为止,除了 JOINS 和 WHERE 子句之外,我对任何事情都很迷茫。我很感激帮助。

SELECT        serviceclass.description, DATEPART(Year, meterread.readdate) AS Year, DATEPART(Month, meterread.readdate) AS Month, SUM(meterread.consumption) 
                     AS Consumption, COUNT(DISTINCT accountservice.account_id) AS Locations
FROM            accountservice INNER JOIN
                     serviceclass ON accountservice.serviceclass_id = serviceclass.serviceclass_id INNER JOIN
                     meterread ON accountservice.accountservice_id = meterread.accountservice_id
WHERE        (@Year = DATEPART(Year, meterread.readdate))
GROUP BY serviceclass.description, DATEPART(Year, meterread.readdate), DATEPART(Month,meterread.readdate)
ORDER BY Year, Month
4

2 回答 2

0

您通常case会使用同时出现在selectandgroup by语句中的语句来执行此操作。就像是:

select (case when serviceclass.description = 'A' then 'B'
             else serviceclass.description
        end) as description
       . . . -- fill in with query here
group by (case when serviceclass.description = 'A' then 'B'
             else serviceclass.description
           end), . . .  -- rest of query goes here
于 2013-08-13T20:20:12.230 回答
0

您可以通过使用CASE语句来实现这一点。

serviceclass.desription在你的SELECTandGROUP BY子句中替换为

CASE
    WHEN serviceclass.description IN ('Desc1','Desc2','Desc3')
        THEN 'JointDescription'
    ELSE serviceclass.description
END

并使用您的三个描述更新 Desc 1 ~ 3 并将联合描述更新为您想要的。

结果:

SELECT CASE
           WHEN serviceclass.description IN ('Desc1','Desc2','Desc3')
               THEN 'JointDescription'
           ELSE serviceclass.description
       END as description, 
       DATEPART(Year, meterread.readdate) AS Year,  
       DATEPART(Month, meterread.readdate) AS Month, 
       SUM(meterread.consumption) AS Consumption, 
       COUNT(DISTINCT accountservice.account_id) AS Locations
FROM accountservice 
INNER JOIN serviceclass ON accountservice.serviceclass_id = serviceclass.serviceclass_id 
INNER JOIN meterread ON accountservice.accountservice_id = meterread.accountservice_id
WHERE        (@Year = DATEPART(Year, meterread.readdate))
GROUP BY CASE
             WHEN serviceclass.description IN ('Desc1','Desc2','Desc3')
                  THEN 'JointDescription'
             ELSE serviceclass.description
         END, 
         DATEPART(Year, meterread.readdate), 
         DATEPART(Month,meterread.readdate)
ORDER BY Year, Month
于 2013-08-13T20:20:35.340 回答