我有一个包含产品列和销售日期的表格,并且想要查询每个产品组的销售间隔的统计数据(最大间隔,最小间隔...),有什么好建议可以做到,欣赏〜
Prod SaleDate
-------------------
A 2013-02-05
D 2013-02-24
B 2013-03-01
A 2013-03-12
D 2013-03-22
A 2013-04-03
D 2013-04-08
. . .
出售间隔是指两个相邻日期之间的天数间隔。
A的售出间隔: DATEDIFF(d,'2013-02-05','2013-03-12') DATEDIFF(d,'2013-03-12','2013-04-03') ...
D的售出间隔: DATEDIFF(d,'2013-02-24','2013-03-22') DATEDIFF(d,'2013-03-22','2013-04-08')
我希望获得售出间隔的平均值,最大值和最小值。
Prod IntervalAvg IntervalMax IntervalMin
-----------------------------------------------------
A xxx xxx xxx
B xxx xxx xxx
C
. . .
答案 0 :(得分:2)
谢谢Kahn的回答给我一个提示。我通过" left outer join"重新实现我的sql server 2000代码。
DECLARE @DATA TABLE (Prod CHAR(1), SaleDate SMALLDATETIME)
INSERT INTO @DATA VALUES ('A','2013-02-05')
INSERT INTO @DATA VALUES ('D','2013-02-24')
INSERT INTO @DATA VALUES ('B','2013-03-01')
INSERT INTO @DATA VALUES ('A','2013-03-12')
INSERT INTO @DATA VALUES ('D','2013-03-22')
INSERT INTO @DATA VALUES ('A','2013-04-03')
INSERT INTO @DATA VALUES ('D','2013-04-08')
SELECT
t.Prod
, MAX(t.Interval) IntervalMax
, MIN(t.Interval) IntervalMin
, AVG(t.Interval) IntervalAvg
FROM
(
SELECT t1.*, DATEDIFF(dd, MAX(t2.SaleDate), t1.SaleDate) Interval
FROM @DATA t1
LEFT OUTER JOIN @DATA t2 ON t1.Prod = t2.Prod AND t1.SaleDate > t2.SaleDate
GROUP BY t1.Prod, t1.SaleDate
)t
GROUP BY t.Prod
ORDER BY t.Prod
答案 1 :(得分:0)
这是一种应该有效的方法:
-- Test data
DECLARE @DATA TABLE (Prod CHAR(1), SaleDate DATE)
INSERT INTO @DATA VALUES ('A','2013-02-05')
,('D','2013-02-24')
,('B','2013-03-01')
,('A','2013-03-12')
,('D','2013-03-22')
,('A','2013-04-03')
,('D','2013-04-08')
-- Actual query
;WITH CTE AS
(SELECT D.*, CA.NextSaleDate
, DATEDIFF(DD, SaleDate, NextSaleDate) DDiff
FROM @DATA D
OUTER APPLY (SELECT MIN(SaleDate) NextSaleDate FROM @DATA B WHERE B.Prod = D.Prod AND B.SaleDate > D.SaleDate) CA)
SELECT DISTINCT Prod, AvgInterval, MaxInterval, MinInterval
FROM CTE C
CROSS APPLY (SELECT AVG(DDiff) AvgInterval, MAX(DDiff) MaxInterval, MIN(DDiff) MinInterval FROM CTE B WHERE B.Prod = C.Prod) CA