我有下表:
+----------+----------+--------------+
| Customer | Month | Had Meeting? |
+----------+----------+--------------+
| John | Jan-15 | N |
| John | Feb-15 | Y |
| John | March-15 | Y |
| John | April-15 | N |
| John | May-15 | N |
| John | June-15 | N |
| John | July-15 | N |
| John | Aug-15 | N |
| John | Sep-15 | N |
| John | Oct-15 | N |
| John | Nov-15 | Y |
| John | Dec-15 | N |
+----------+----------+--------------+
我希望运用一个观察客户的逻辑,检查他是否在3个月的滚动期内举行任何会议。此期间是指会议可能发生的动态时间间隔。即 - 在5月15日'记录我希望看一下2月到7月之间的时期。
如果有超过1次会议,我希望返回最早的会议。
即,在1月15日,我想看看1月到3月之间的inerval,它捕获了2次会议,我想要回到两者中较早的时间(2月)。
2月份我想看看1月到4月之间的时间间隔(前2个月和2个月之后) - 再次,它应该回到2月的会议。
3月份,我希望看一月到五月(这实际上是2个月的全职时间,之后我需要捕捉2个月) - 再次回到2月份。
我希望从该数据集中获取的最终结果是2月和11月的会议。 我想我需要这样的东西:
row_number() over(partition by Customer order by Sale_made, Month Rows between 2 preceding and 2 following)
但是row_number不能用作窗口函数。
我正在使用TD v 13.0。
感谢您的帮助。
阿萨夫。
答案 0 :(得分:1)
好像你想要在有会议时返回一行,而前一行Had Meeting?
至少是三个月前。
SELECT *
FROM tab
WHERE "Had Meeting?" = 'Y' -- no need for rows without meeting
QUALIFY
COALESCE(MAX("Month") -- previous row's date (i.e. LAG syntax)
OVER (PARTITION BY Customer
ORDER BY "Month"
ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING)
,DATE '0001-01-01') -- otherwise 1st row will return NULL
< ADD_MONTHS("Month", -3) -- three month before the current row's date
答案 1 :(得分:0)
尝试一下,我必须转换日期,所以他们现在是varchar
create table #table(
Customer varchar(50),
[Month] varchar(50),
[Had Meeting] varchar(1)
)
INSERT INTO #table (Customer, [Month], [Had Meeting])
VALUES
('John', 'Jan-15', 'N'),
('John', 'Feb-15', 'Y'),
('John', 'March-15', 'Y'),
('John', 'April-15', 'N'),
('John', 'May-15', 'N'),
('John', 'June-15 ', 'N'),
('John', 'July-15 ', 'N'),
('John', ' Aug-15', 'N'),
('John', ' Sep-15', 'N'),
('John', ' Oct-15', 'N'),
('John', 'Nov-15', 'Y'),
('John', 'Dec-15', 'N')
DECLARE @searchdate datetime = '2015-05-01 00:00:00.000'
SELECT TOP 1
Customer,
MIN([Month]) AS [Month],
[Had Meeting]
FROM #table
WHERE DATEPART(YEAR, @searchdate) = DATEPART(YEAR, DATEADD(YEAR, -1, GETDATE()))
AND [Had Meeting] = 'Y'
AND CONVERT(datetime, '1-' + [Month], 104) >= DATEADD(MONTH, -2, @searchdate)
AND DATEPART(MONTH, CONVERT(datetime, '1-' + [Month], 104)) <= (DATEPART(MONTH, @searchdate) + 2)
AND Customer = 'John'
GROUP BY Customer,
[Month],
[Had Meeting]
&#13;