0

How can I group by the following query by customerId

select
(SELECT SUM(Purchase) FROM Customers where type in (17,21)) as 'Purchase'
,(SELECT SUM(Point) FROM Customers) as 'Point'
FROM CUSTOMERS
GROUP BY Customers.CustomerID

Charlieface
  • 52,284
  • 6
  • 19
  • 43

3 Answers3

4

Looks like you just want conditional aggregation, which you can do by placing CASE WHEN... inside a SUM.

SELECT
  c.CustomerId
  SUM(CASE WHEN c.type IN (17, 21) THEN c.Purchase END) AS Purchase,
  SUM(c.Point) AS Point
FROM CUSTOMERS c
GROUP BY
  c.CustomerID;

Note the use of a table alias to make it more readable, and do not use '' to quote column names, only [] and only where necessary.

Charlieface
  • 52,284
  • 6
  • 19
  • 43
0

Remove the From Customers in the Selects and Move the Where to the root of the query

Change your query to

SELECT
[CustomerID] as 'CustomerID'
, SUM([Purchase]) as 'Purchase'
, SUM([Point]) as 'Point'
FROM [CUSTOMERS]
WHERE [type] in (17,21)
GROUP BY [Customers].[CustomerID]

This will give you

CustomerID  Purchase    Point
1           246         3
2           23434       7
Pierre
  • 65
  • 8
-1

If you're trying to get the total Purchase and total Points per customer, then you need to include the CustomerId in the Purchase sub-query as well as in your main query.

A key thing to remember regarding Group By is that all non-aggregate columns have to be included in it. Therefore in your case, you'd have to group by the Purchase as well.

Your final query would look like:

select c.CustomerId, 
(SELECT SUM(Purchase) FROM Customers where type in (17,21) and CustomerId = c.CustomerId) as 'Purchase'
, SUM(Point) as 'Point'
FROM CUSTOMERS c
GROUP BY c.CustomerID, Purchase
CoderSivu
  • 141
  • 2
  • 7
  • But why bother with the subquery at all? Why *not* use conditional aggregation, it's a standard technique? Also you don't need to and probably should not group by `Purchase` as it isn't used in the `SELECT`, the only mention of `Purchase` refers to the *subquery's* `Purchase` column. – Charlieface Jul 23 '23 at 11:07
  • I take it you missed my comment on your answer :) – CoderSivu Jul 23 '23 at 11:24
  • I didn't miss it, I just don't get why you would even consider the above, as mentioned. I just mean: isn't obvious that OP wants conditional aggregation? – Charlieface Jul 23 '23 at 11:26