简体   繁体   English

对Group By子句使用案例声明

[英]Use a case statement for Group By clause

I have been trying to do a query using Microsoft SQL Server 2008 R2, grouping the total sum of points by intervals. 我一直在尝试使用Microsoft SQL Server 2008 R2进行查询,并按间隔对总点数进行分组。 However, I can´t get this to work. 但是,我无法使它正常工作。 This is my code: 这是我的代码:

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

With this error: 出现此错误:

Msg 156, Level 15, State 1, Line 17
Incorrect syntax near the keyword 'GROUP'.

I have been reading different posts, and had come to the conclusion that is IS possible to do this kind of query, by placing the CASE statement within a subquery (I came to this conclusion reading this post). 我一直在阅读不同的文章,并得出结论,可以通过将CASE语句放在子查询中来进行这种查询(我在阅读这篇文章时得出了这个结论)。 Clearly I am doing something wrong. 显然我做错了。 Any help? 有什么帮助吗?

Your problem is just that you need to provide an alias for the subquery, like so: 您的问题只是需要为子查询提供别名,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM