使用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
语句。也许我想要在单个查询中实现的目标是什么?
答案 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)
您是否尝试过使用带有SUM
和OVER()
条款的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