需要针对此方案的SQL查询

时间:2016-04-23 16:25:55

标签: sql sql-server sql-server-2008 tsql

我有一张桌子如下。我需要结果AssetID甚至不能完成一项任务。

CREATE TABLE #T(AssetId INT,TaskName varchar(100),StartTime DATE,EndTime date)
go

insert into #t(AssetId,TaskName,StartTime,EndTime) values(10,'task1','2016-01-11','2016-04-12')</b>
insert into #t(AssetId,TaskName,StartTime,EndTime) values(10,'task2','2016-01-11',NULL)
insert into #t(AssetId,TaskName,StartTime,EndTime) values(10,'task3','2016-01-11','2016-12-11')</b>
insert into #t(AssetId,TaskName,StartTime,EndTime) values(11,'task4','2016-01-11','2016-04-12')</b>
insert into #t(AssetId,TaskName,StartTime,EndTime) values(11,'task1','2016-01-11','2016-04-12')</b>
insert into #t(AssetId,TaskName,StartTime,EndTime) values(11,'task2','2016-01-11',NULL)</b>
insert into #t(AssetId,TaskName,StartTime,EndTime) values(12,'task1','2016-01-11',null)</b>
insert into #t(AssetId,TaskName,StartTime,EndTime) values(12,'task2','2016-01-11',null)</b>
insert into #t(AssetId,TaskName,StartTime,EndTime) values(12,'task3','2016-01-11',null)</b>
insert into #t(AssetId,TaskName,StartTime,EndTime) values(13,'task1','2016-01-11',null)</b>
insert into #t(AssetId,TaskName,StartTime,EndTime) values(13,'task2','2016-01-11',null)</b>

所以结果需要如下

12  task1   11-01-2016  NULL
12  task2   11-01-2016  NULL
12  task3   11-01-2016  NULL
13  task1   11-01-2016  NULL
13  task2   11-01-2016  NULL

3 个答案:

答案 0 :(得分:2)

如果您需要 assetid ,请使用group by

select assetid
from #t
group by assetid
having count(endtime) = 0;

如果你想要行,那么使用窗口函数:

select t.*
from (select t.*, count(endtime) over (partition by assetid) as cntet
      from #t t
     ) t
where cntet = 0;

答案 1 :(得分:2)

@Gorden的答案非常好,可能会产生更好的查询计划,因为它只扫描一次表。

但只是向您介绍非常有用的SELECT * FROM #T AS a WHERE NOT EXISTS (SELECT 1 FROM #T AS b WHERE a.AssetId = b.AssetId AND b.EndTime IS NOT NULL) 子句。可以使用这样的存在来完成。

T operator...

答案 2 :(得分:0)

请让我知道下面的查询是否对此有效。

Select * from #T where assetID not in (Select distinct assetid from #T where endtime is not null )