我有两张桌子,
tblCustomer
CustomerID(PK),FirstName,Surname)
tblPurchases
PurchaseID(PK),PurchaseDate,Qty,CustomerID(FK)。
我想以下列方式显示自上次购买后五(5)天或更长时间内购买产品的所有客户。
FirstName diff in days since last purchase
Alex 7
谢谢!
答案 0 :(得分:0)
尝试使用以下查询。
SELECT FirstName, DATEDIFF(DAY, t.PurchaseDate, getdate()) as 'diff in days since last purchase'
FROM tblCustomer c
JOIN (SELECT CustomerID, MAX(PurchaseDate)PurchaseDate
FROM tblPurchases
GROUP BY CustomerID )t ON c.CustomerID=t.CustomerID
WHERE DATEDIFF(DAY, PurchaseDate, getdate())>5
答案 1 :(得分:0)
SELECT FirstName,
DATEDIFF(DAY, t.PurchaseDate, getdate()) 'diff in days since last purchase'
FROM tblCustomer c
JOIN (SELECT CustomerID, MAX(PurchaseDate)PurchaseDate
FROM tblPurchases
GROUP BY CustomerID )t ON c.CustomerID=t.CustomerID
WHERE DATEDIFF(DAY, t.PurchaseDate, getdate())>5
答案 2 :(得分:0)
通过加入两个表格,根据每个CustomerId
的最后购买日期给出一个行号。
然后使用current date
找出DATEDIFF
和PurchaseDate
之间的天数差异。
并给出WHERE
中的天数差异子句。
<强>查询强>
;WITH CTE AS(
SELECT [rn] = ROW_NUMBER() OVER(
PARTITION BY t.[CustomerID]
ORDER BY t.[PurchaseDate] DESC
), t.[CustomerID], t.[FirstName], t.[PurchaseDate]
FROM (
SELECT t1.[CustomerID], t1.[FirstName], t2.[PurchaseDate]
FROM [tblCustomer] t1
JOIN [tblPurchases] t2
ON t1.[CustomerID] = t2.[CustomerID]
)t
)
SELECT [FirstName],
DATEDIFF(DAY, [PurchaseDate], GETDATE()) AS [diff in days since last purchase]
FROM CTE
WHERE [rn] = 1
AND DATEDIFF(DAY, [PurchaseDate], GETDATE()) > 5;
答案 3 :(得分:0)
;WITH T AS
(
SELECT
*,
DATEDIFF(DAY, [PurchaseDate], GETDATE()) AS DiffInDays
FROM @tblPurchases
WHERE DATEDIFF(DAY, [PurchaseDate], GETDATE()) > 5
)
SELECT
C.FirstName,
MAX(DiffInDays) AS DiffInDays
FROM T
LEFT JOIN @tblCustomer C ON T.CustomerId=C.CustomerId
GROUP BY C.FirstName