有多个具有相同ID但不同的Condition_Date的equipment.ID,我只想显示每个唯一Equipment.ID的最新条件日期。
Select equipment.ID as EquipmentID,
equipment.DESCRIPTION,
CONDITION_DATE,
CONDITION_TYPE.DESCRIPTION
from CONDITION
LEFT JOIN EQUIPMENT ON condition.GUID_EQUIPMENT = EQUIPMENT.GUID
LEFT JOIN Condition_type ON Condition.GUID_CONDITION_TYPE = condition_type.guid
WHERE IS_DEACTIVATED = '0'
AND equipment.HAS_CONDITION_CONTROL = '1'
AND Condition_type.DESCRIPTION is not null
Equipment ID | Condition_Date
3345.02 | 2013-08-29
3345.02 | 2009-05-20
3346 | 2019-07-05
3345.02 | 2001-01-01
3346 | 2008-08-02
我希望它仅显示
Equipment ID | Condition_Date
3345.02 | 2013-08-29
3346 | 2019-07-05
答案 0 :(得分:1)
接下来,在日期字段上使用MAX和GROUP BY ID进行汇总:
auth
答案 1 :(得分:0)
ROW_NUMBER()
是您在SQL Server上使用此应用程序的朋友。
SELECT * FROM (
Select equipment.ID as EquipmentID,
equipment.DESCRIPTION,
CONDITION_DATE,
CONDITION_TYPE.DESCRIPTION,
ROW_NUMBER() OVER (Partition by equipment.ID ORDER BY CONDITION_DATE DESC) AS rownum
from CONDITION
LEFT JOIN EQUIPMENT ON condition.GUID_EQUIPMENT = EQUIPMENT.GUID
LEFT JOIN Condition_type ON Condition.GUID_CONDITION_TYPE = condition_type.guid
WHERE IS_DEACTIVATED = '0'
AND equipment.HAS_CONDITION_CONTROL = '1'
AND Condition_type.DESCRIPTION is not null ) WHERE rownum = 1
在您的简约示例中,这等效于在分组时也使用MAX
类型解决方案,但是如果您要有条件地从与较高CONDITION_DATE
相关的记录中提取其他信息,则您需要ROW_NUMBER()
。
工作方式:
ROW_NUMBER()
为返回的每一行分配一个行号(按equipment.ID
划分),按CONDITION_DATE
的顺序排列。因此,最新记录集将始终具有ROW_NUMBER()
1。您可以通过在WHERE部分中选择它来滥用它。答案 2 :(得分:0)
如果要使用所有设备,则该表应该是LEFT JOIN
链中的第一个表。
但是,您正在检查条件类型是否匹配,因此LEFT JOIN
甚至不合适。
对于这种情况,我建议在row_number()
表的子查询中使用conditions
:
select e.ID as EquipmentID, e.DESCRIPTION,
c.CONDITION_DATE,
ct.DESCRIPTION
from equipement e join
(select c.*,
row_number() over (partition by guid_equipment order by c.condition_date desc) as seqnum
from condition c
) c
on c.GUID_EQUIPMENT = e.GUID and
seqnum = 1 join
condition_type ct
on c.GUID_CONDITION_TYPE = ct.guid
where e.IS_DEACTIVATED = 0 and -- looks like a number, so no single quotes
e.HAS_CONDITION_CONTROL = 1 and -- looks like a number, so no single quotes
ct.DESCRIPTION is not null