我一直在尝试使用Microsoft SQL Server 2008 R2进行查询,按间隔对总点数进行分组。但是,我无法让这个工作。这是我的代码:
SELECT interval_total, COUNT(*) FROM(
SELECT clients.clientId, total.TotalPoints,
CASE
WHEN TotalPuntos >=5000 THEN 5000
WHEN TotalPuntos >= 1000 THEN 1000
WHEN TotalPuntos >= 500 THEN 500
WHEN TotalPuntos >= 100 THEN 100
ELSE 0
END as interval_total
FROM
[TotalSumOfPoints] total,
[Client] clients
WHERE total.clientId = clients.clientId
AND clients.cardId LIKE '2001%')
GROUP BY interval_total
出现此错误:
Msg 156, Level 15, State 1, Line 17
Incorrect syntax near the keyword 'GROUP'.
我一直在阅读不同的帖子,并得出结论是可以通过将CASE语句放在子查询中来进行这种查询(我得出这个结论,阅读this帖子)。显然我做错了什么。有什么帮助吗?
答案 0 :(得分:4)
您的问题只是您需要为子查询提供别名,如下所示:
SELECT interval_total, COUNT(*) FROM(
SELECT clients.clientId, total.TotalPoints,
CASE
WHEN TotalPuntos >=5000 THEN 5000
WHEN TotalPuntos >= 1000 THEN 1000
WHEN TotalPuntos >= 500 THEN 500
WHEN TotalPuntos >= 100 THEN 100
ELSE 0
END as interval_total
FROM
[TotalPuntosPorCuenta] total,
[SanRoque].[dbo].[Socio] clients
WHERE total.clientId = clients.clientId
AND clients.cardId LIKE '2001%') tbl /* <--- here */
GROUP BY interval_total