我想过滤SQL中的数据,以便我只有IsReady字段为真的每个厚度的最新行。
编辑:我正在为所有需要知道的人使用MSSQL 2008服务器我的数据是这样的:
+--+----------+-----------+----------+-------+
|ID|SupplierID|ThicknessID|DateTime |IsReady|
+--+----------+-----------+----------+-------+
|01|1 |1 |01/01/1990|1 |
|02|1 |1 |01/01/2012|0 |
|03|1 |2 |01/01/1990|1 |
|04|1 |2 |01/01/2012|1 |
根据提供的数据,SQL代码应返回以下内容:
+--+----------+-----------+----------+-------+
|ID|SupplierID|ThicknessID|DateTime |IsReady|
+--+----------+-----------+----------+-------+
|01|1 |1 |01/01/1990|1 |
|04|1 |2 |01/01/2012|1 |
希望这是足够的信息让你理解,如果不是只是评论
答案 0 :(得分:2)
SELECT A.* FROM TABLE A,
(SELECT ThicknessID,MAX(DateTime) AS MaxDateTime
FROM TABLE
WHERE IsReady=1
GROUP BY ThicknessID
) B
WHERE A.ThicknessID=B.ThicknessID AND
A.MaxDateTime = B.DateTime;
答案 1 :(得分:1)
SELECT t.*
FROM Table t
WHERE IsReady=1
AND t.ID=(SELECT TOP 1 t2.ID
FROM Table t2
WHERE t2.IsReady=1
AND t.ThicknessID=t2.ThicknessID
ORDER BY DateTime DESC)
答案 2 :(得分:0)
假设您希望每个SupplierID
分别包含行:
select t.ID,
t.SupplierID,
t.ThicknessID,
t.[DateTime],
t.IsReady
from MyTable t
inner join (
select SupplierID,
ThicknessID,
max([DateTime]) as MaxDateTime
from MyTable
where IsReady = 1
group by SupplierID,
ThicknessID
) a on t.ThicknessID = a.ThicknessID
and t.SupplierID = a.SupplierID
and t.MaxDateTime = a.[DateTime]
答案 3 :(得分:0)
所选查询将正常工作。但是这个查询将更快地运行并且将使用更少的资源
select distinct (SupplierID, ThicknessID) * from
(
select * from Table1 where IsReady = 1
order by [DateTime] desc
)
我试过这个并且性能更高