我在sql server中有一个问题。我有一些像
这样的记录PKId EquipmentID StudentId Issueddate Returneddate
1 116 230 2014-01-14 17:14:58.940 2014-01-18 14:12:038.876
2 116 237 2014-01-14 17:14:58.940 NULL
3 117 400 2014-01-14 17:14:58.940 2014-01-18 14:12:038.876
这里的EquipmentID和StudentId是外键。我们需要写一个查询,它给我们基于Returneddate的数据。我们需要检查条件一,如第一行equipmentid是116并且它被分配给studentId 230,其中Returneddate不为null意味着现在这116个设备是免费的意味着它是无人值守但在下一行同样的设备被分配给学生237并且hiis返回日期是NULL意味着这个设备被绑定给某人并且在最后一种情况下设备117分配给studentid 400并且它的返回日期是not null表示它可用。
所以我们只需要显示那些可用的记录。如果我把这个案例作为例子那么它会给我
3 117 400 2014-01-14 17:14:58.940 2014-01-18 14:12:038.876
行作为输出。
我试过:
select * from Equipment where (EquipmentID not in (select EquipmentID
from PEquip where Returneddate is null))
请帮帮我。
希望你明白。
答案 0 :(得分:1)
试试这个:
select * from theTable t1 where returneddate =
(select max Issueddate from theTable t2 where t1.EquipmentId = t2.EquipmentId)
and returneddate is not NULL;
答案 1 :(得分:1)
如果我做得对,你需要EquipmentID
,其中没有行Returneddate
的行。
SELECT * FROM T as T1
WHERE NOT EXISTS (SELECT * FROM T
WHERE EquipmentID=T1.EquipmentID
AND Returneddate IS NULL)
答案 2 :(得分:1)
select * from EuipmentDetails where EquipmentID
not in (select EquipmentID from EuipmentDetails where Returneddate is NULL )
答案 3 :(得分:1)
假设PkId
的顺序与数据的年表一致,我会选择
SELECT PKId, EquipmentID, StudentId, Issueddate, Returneddate
FROM Equipment E
INNER JOIN (SELECT MAX(PKId) AS PKId FROM Equipment GROUP BY EquipmentId) AS T
ON E.PKId = T.PKId
WHERE E.ReturnedDate IS NOT NULL
逻辑:选择每个EquipmentId
的最新条目, IF 最新条目的返回日期不为空。