Monday, October 28, 2013

SQL query


CREATE TABLE test (Person VARCHAR(20), Action VARCHAR(10), [Date] DATE)
INSERT INTO test
VALUES ('MAX','Sale','20100720'),
('MAX','Sale','20101026'),
('MAX','Sale','20101103'),
('MAX','Sale','20110401'),
('MAX','No Sale','20110528'),
('MAX','Sale','20110613'),
('MAX','Sale','20110711'),
('MAX','Sale','20110819'),
('MAX','No Sale','20111001'),
('MAX','No Sale','20111209'),
('MAX','Sale','20120201'),
('MAX','No Sale','20120201'),
('MAX','Sale','20120207'),
('MAX','Sale','20120213'),
('MAX','No Sale','20130706');
;with mycte as
(
select *, row_number() Over(order By [Date],Action Desc) rn1
, row_number() Over(partition by Action order By Date, aCTION desc) rn2
, row_number() Over(order By [Date],Action DESC ) - row_number() Over(Partition by Action Order By [Date] ) rn3
from test)
, mycte2 as
( Select *,row_number() Over(partition by rn3 order By ACTION DESC,[Date]) rn4
, row_number() Over(partition by rn3 order By Action ) rn5
from mycte )
SELECT Person,Action,[Date],'Y' AS flag
FROM mycte2
WHERE rn4 = 1 OR rn5 = 1
ORDER BY [Date], ACTION DESC

DROP TABLE test
/*
Person Action Date flag
MAX Sale 2010-07-20 Y
MAX No Sale 2011-05-28 Y
MAX Sale 2011-06-13 Y
MAX No Sale 2011-10-01 Y
MAX Sale 2012-02-01 Y
MAX No Sale 2012-02-01 Y
MAX Sale 2012-02-07 Y
MAX No Sale 2013-07-06 Y
*/


No comments:

Post a Comment