0

使用 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语句。也许我想要实现的目标在单个查询中是不可能的?

4

2 回答 2

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() )
于 2013-11-13T15:21:10.510 回答
0

您是否尝试过使用带有 aSUMOVER()子句的 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
于 2013-11-13T15:23:29.433 回答