Soph
Soph

Reputation: 2915

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. 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). Clearly I am doing something wrong. Any help?

Upvotes: 0

Views: 6539

Answers (1)

Eric Petroelje
Eric Petroelje

Reputation: 60498

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

Upvotes: 4

Related Questions