关于sql server:带分组和计数的Sql

Sql with group by and count

本问题已经有最佳答案,请猛点这里访问。

我有一个具有group by的sql select查询。 分组不起作用。 我想在group by语句后计算所有记录。 有没有办法直接从sql? 例如,我想计算mobtel和金额的总和。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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);


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
SELECT
    AGENCY
    , DSM
    , Channel
    , COUNT(A.MSISDN)
    , SUM(B.AMOUNT)
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