假设我有一个这样的SQL Server表:
Event | Item1 | Item2 | Status
-------------------------------------------
1 Parent1 Child1 1
2 Parent1 Child2 1
3 Parent2 Child1 1
4 Parent2 Child2 1
5 Parent3 Child1 1
6 Parent3 Child2 0
7 Parent4 Child1 1
8 Parent4 Child1 1
9 Parent4 Child2 0
我想要一个给我以下内容的查询:
所以最终的结果应该是这样的:
6, Parent3, Child2, 0
9, Parent4, Child2, 0
5, Parent3, Child1, 1
8, Parent4, Child1, 1
此解决方案位于SQL 2008 R2中。 我对临时表,联合,联接等开放。我无法更改架构。非常感谢任何帮助。
答案 0 :(得分:1)
这应该可行,但我不知道它是否真的针对大数据进行了优化。
CREATE TABLE #tab (id int, Item1 varchar(255), Item2 varchar(255), Status bit)
INSERT INTO #tab VALUES
(1,'Parent1','Child1', 1 ),
(2,'Parent1','Child2', 1 ),
(3,'Parent2','Child1', 1 ),
(4,'Parent2','Child2', 1 ),
(5,'Parent3','Child1', 1 ),
(6,'Parent3','Child2', 0 ),
(7,'Parent4','Child1', 1 ),
(8,'Parent4','Child1', 1 ),
(9,'Parent4','Child2', 0 )
SELECT * INTO #filter FROM #tab WHERE Status = 0
SELECT * INTO #results FROM #tab
WHERE
Id IN (
SELECT MAX(ID) FROM #tab
WHERE Item2 = 'Child1' AND Status = 1 AND Item1 IN (SELECT Item1 FROM #filter)
GROUP BY Item1
)
SELECT * FROM #filter
UNION
SELECT * FROM #results
答案 1 :(得分:1)
这需要sqlserver 2005
;WITH a as
(
SELECT Event, Item1, Item2, Status,
min(status) over( partition by item1) lowstatus,
max(Event) over( partition by item2, status) hievent
FROM table
)
SELECT Event, Item1, Item2, Status
FROM a
WHERE status = 0
or Item2 = 'Child1' and Status = 1 and lowstatus = 0 and hievent = Event