T-SQL运行总和

时间:2019-06-28 18:52:17

标签: sql sql-server-2008

请考虑以下形状的表(wallet, client, date),其中walletclientstrings,而date是直到今天的任何日期。 假设有人想获得唯一客户和客户今年的每个月的总和,按钱包和月份分组。 我已经尝试了几种方法,包括分区,但是我无法使其正常工作。

结果将类似于:

+------------+---------+------------+---------+
|    Wallet  |  Unique |  Count     | Month   |
+------------+---------+------------+---------+
| Wallet1    | 2       |   5        |   1     | - For < 01022019
+------------+---------+------------+---------+
| Wallet1    | 3       |   7        |   2     | - For < 01032019
+------------+---------+------------+---------+

以此类推。我尝试了很多事情,甚至进行了分区,但都失败了。我只设法在日期以下使用WHERE使其变成几个小查询,这绝对糟糕,例如。

INSERT INTO 
    tmp_tbl_filtered
SELECT
    [Wallet],
    COUNT(DISTINCT [Client]) AS [unique],
    COUNT([Client]) AS [count],
    1 AS [month]
FROM
    tmp_tbl
WHERE [Date] < '20190201'
GROUP BY  [Wallet]
ORDER BY [Wallet]

INSERT INTO 
    tmp_tbl_filtered
SELECT
    [Wallet],
    COUNT(DISTINCT [Client]) AS [unique],
    COUNT([Client]) AS [count],
    2 AS [month]
FROM
    tmp_tbl
WHERE [Date] < '20190301'
GROUP BY  [Wallet]
ORDER BY [Wallet]

2 个答案:

答案 0 :(得分:0)

如果我做对了

SELECT [Wallet], [month]
   , SUM([unique]) OVER(PARTITION BY [Wallet] ORDER BY [month]) [unique_rt]
   , SUM([count]) OVER(PARTITION BY [Wallet] ORDER BY [month]) [count_rt]
FROM (
    --  group data of the current year 2019 by wallet and month
    SELECT 
        [Wallet],
        DATEPART(month,[Date]) AS [month],
        COUNT(DISTINCT [Client]) AS [unique],
        COUNT([Client]) AS [count]
    FROM
        tmp_tbl
    WHERE [Date] >= '20190101'
    GROUP BY [Wallet], DATEPART(month,[Date])
) t
ORDER BY [Wallet], [month]

答案 1 :(得分:0)

我看不到累积部分在哪里发挥作用。

SELECT YEAR(date), MONTH(date), Wallet,
       COUNT(DISTINCT [Client]) AS [unique],
       COUNT([Client]) AS [count],
FROM tmp_tbl
WHERE [Date] < '20190301'
GROUP BY YEAR(date), MONTH(date), [Wallet]
ORDER BY Wallet, YEAR(date), MONTH(date)