I have an sql select query that has a group by. Group by doesn't work. I want to count all the records after the group by statement. Is there a way for this directly from sql? For example, I want to count mobtel and the total sum of amount.
SELECT
--DISTINCT
B.ABS_CHANNEL_NAME AS AGENCY,
B.ABS_REGION AS REGION,
A.MSISDN AS [Mobtel],
A.Activation_date AS [Activation Date],
LEFT(B.DATE, 8) AS [Top Up Date],
DATEDIFF(d, CONVERT(char(10), A.Activation_date,121), CONVERT(char(10), B.DATE,121)) AS [Days Elapsed],
B.Amount,
C.DSM as [DSM],
C.Channel as [CHANNEL]
FROM [ODS_BI_R].[dbo].[R_Activation] A
JOIN [ODS_Raw].[dbo].[D_TopUpTransaction_Amax] B
ON A.MSISDN = CONCAT('63', B.B_NUM)
JOIN [dbo].[Retailer_Sims] C
on B.A_NUM = C.RETAILERID
WHERE Activation_date LIKE '%201701%'
AND B.AMOUNT <> '0:00'
AND A.SEGMENTATION = 'Prepaid'
AND CONVERT(INT,AMOUNT) >= 20
AND DATEDIFF(d, CONVERT(char(15), A.Activation_date,121), CONVERT(char(15), B.DATE,121)) BETWEEN 0 AND 30
---Group BY AGENCY, DSM, Channel, count(A.MSISDN), sum(B.AMOUNT)
ORDER BY A.Activation_date, A.MSISDN, LEFT(B.DATE, 8);
GROUP BY
actually does. WithGROUP BY AGENCY, DSM, Channel
you'd say "give me one result row per AGENCY, DSM, and Channel, which may be what you want.GROUP BY ..., count(A.MSISDN), sum(B.AMOUNT)
however doesn't make sense, as the count and the sum are results. You'd put them in theSELECT
clause hence. Moreover you'd remove things from yourSELECT
clause, such asB.Amount
, because there can be many amounts per group, so you can only show an aggregation, such asSUM(B.Amount)
.