我有一个按字段描述分组的查询。 (总共有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
答案 0 :(得分:0)
您通常会使用case
语句执行此操作,该语句同时包含select
和group 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
答案 1 :(得分:0)
您可以使用CASE
语句来实现此目的。
使用
替换serviceclass.desription
和SELECT
子句中的GROUP 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