T-SQL返回未组合记录的总和

时间:2013-11-13 15:10:25

标签: sql-server-2008 tsql group-by having

使用SQL Server 2008:我正在尝试撰写过去一周发生的客户交易报告,报告价格超过1000美元。我有以下SQL查询,它会给我正确的记录,但显然会聚合结果:

SELECT 
   customerID, 
   CAST(createdAt AS DATE) AS transactionDate, 
   SUM(transactionAmount) as dailyTotal,
FROM transactions
WHERE createdAt > DATEADD( DAY, -7, GETDATE() )
GROUP BY clientID, CAST(createdAt AS DATE)
HAVING SUM(transactionAmount) > 1000

导致类似:

| customerID | transactionDate | dailyTotal |
|       1    |      2013-11-01 |       1212 | 
|       2    |      2013-11-01 |      10002 |
...
|       1    |      2013-11-02 |       5212 |

但是,我需要获取包含这些聚合结果的单个记录,但显然不能省略GROUP BY语句。也许我想要在单个查询中实现的目标是什么?

2 个答案:

答案 0 :(得分:0)

你想要这样的东西吗?

SELECT t.customerID, 
       t.createdAt, 
       t.transactionAmount
FROM transactions t
INNER JOIN (
    SELECT 
       customerID, 
    FROM transactions
    WHERE createdAt > DATEADD( DAY, -7, GETDATE() )
    GROUP BY clientID, CAST(createdAt AS DATE)
    HAVING SUM(transactionAmount) > 1000
) a
ON a.customerID = t.customerID
WHERE t.createdAt > DATEADD( DAY, -7, GETDATE() )

答案 1 :(得分:0)

您是否尝试过使用带有SUMOVER()条款的CTE?

;WITH SalesAgg AS     
(
  SELECT 
     customerID, 
     TransactionDate = CAST(createdAt AS DATE), 
     TransactionAmount,
     TotalSum = SUM(transactionAmount) OVER(PARTITION BY ClientID, CAST(CreatedAt AS DATE) ORDER BY ClientID)
  FROM transactions
  WHERE createdAt > DATEADD( DAY, -7, GETDATE())
)
SELECT
   CustomerID, TransactionDate, TransactionAmount, TotalSum
FROM
   SalesAgg
WHERE
   TotalSum > 1000.0