0

我一直在尝试使用 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 语句放在子查询中来执行这种查询(我在阅读这篇文章时得出了这个结论)。显然我做错了什么。有什么帮助吗?

4

1 回答 1

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
于 2012-05-29T15:02:24.933 回答