Sql with group by和count

时间:2017-03-27 02:16:03

标签: sql sql-server

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

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 个答案:

答案 0 :(得分:0)

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