我有一个带有重复任务的SQL表。例如:
+------------------+----+--------------+
| Task | ID | RecurranceID |
+------------------+----+--------------+
| Take Out Garbage | 1 | 0 |
| Order Pizza | 2 | 0 |
| Eat Breakfast | 3 | 1 |
| Eat Breakfast | 4 | 1 |
| Eat Breakfast | 5 | 1 |
| Order Pizza | 6 | 0 |
+------------------+----+--------------+
RecurranceID为0的任何内容都不是重复性任务,但是否则是一项重复性任务。
如何在定期任务中显示限制为一行的所有任务?
我希望结果集显示:
+------------------+----+
| Task | ID |
+------------------+----+
| Take Out Garbage | 1 |
| Order Pizza | 2 |
| Eat Breakfast | 3 |
| Order Pizza | 6 |
+------------------+----+
使用SQL Server 2012
谢谢!
答案 0 :(得分:1)
;WITH MyCTE AS
(
SELECT Task,
ID,
ROW_NUMBER() OVER (PARTITION BY TASK ORDER BY ID) AS rn
FROM Tasks
)
SELECT *
FROM MyCTE
WHERE rn = 1
您的示例数据不清楚,但您可能还需要在RecurranceID
子句中应用PARTITION BY
,如下所示:
;WITH MyCTE AS
(
SELECT Task,
ID,
RecurranceID,
ROW_NUMBER() OVER (PARTITION BY TASK,RecurranceID ORDER BY ID) AS rn
FROM Tasks
)
SELECT *
FROM MyCTE
WHERE rn = 1
OR RecurranceID = 0
答案 1 :(得分:1)
您似乎希望返回所有非重复性任务,以及每个周期性任务的单行(无论它是否与非重复性任务共享名称)。你在寻找:
SELECT Task, ID
FROM RecurringTaskTable
WHERE RecurrenceID = 0
UNION ALL
SELECT Task, MIN(ID) AS ID
FROM RecurringTaskTable
WHERE RecurrenceID <> 0
GROUP BY Task
答案 2 :(得分:0)
试试这个:
select distinct task
, DENSE_RANK () OVER (order by task) dr
from tasks
答案 3 :(得分:0)
希望这有助于,
DECLARE @test TABLE(Task VARCHAR(30),
ID INT,
RecurranceID INT)
INSERT INTO @test
VALUES('Take Out Garbage', '1', '0'),
('Order Pizza', '2', '0'),
('Eat Breakfast', '3', '1'),
('Eat Breakfast', '4', '1'),
('Eat Breakfast', '5', '1'),
('Order Pizza', '6', '0')
;WITH cte_OneofEach AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY Task ORDER BY ID DESC) AS rn
FROM @test
WHERE RecurranceID = '1'
)
SELECT Task,ID,RecurranceID
FROM @test
WHERE RecurranceID = '0'
UNION
SELECT Task,ID,RecurranceID
FROM cte_OneofEach
WHERE rn = 1