我遇到了这个问题。 我的查询中有一些重复,因为有些记录是在内部和外部同时进行的。我更喜欢在室外,但在内部没有入口的情况下,外面的一些更好。
从产品
中选择ID,日期和地点id date location
----------
2 01/01/2012 in-house
2 05/01/2012 outside <- in this situation i want to keep just in-house
id date location
----------
4 01/01/2012 in-house
5 03/01/2012 outside <- in this situation i want to keep both since there is no db entry for id=5 therefor i have just info from outside
有人可以帮忙吗?
答案 0 :(得分:1)
执行此操作的一种方法是从表到自身执行完全外部联接,然后使用合并。
Select
COALESCE(Inside.Id, outside.id) Id,
COALESCE(Inside.date, outside.date) Date,
COALESCE(Inside.location, outside.location) Location
From
prod Inside
FULL OUTER JOIN prod Outside
ON Inside.id = Outside.iD
and Inside.location <> Outside.Location
Where
(Inside.Location = 'in-house'
or
Inside.Location is null)
and
(outside.Location = 'outside'
or
outside.Location is null)
注意:
如果您的字段可以为空,则可能需要使用Case语句而不是coalesce,并使用ID字段来确定要使用的表。以日期为例
CASE WHEN Inside.Id is not null THEN Inside.date ELSE outside.date END date
正如Dems所说,这也假定{id, location}
是唯一的。
更新
由于您使用的是SQL Server且{ID,Location}不是唯一的,并且您想要最大日期值并始终在室外选择,因此您可以在此处有效使用ROW_NUMBER/WHERE RowNumber = 1
,先订购在位置,然后按日期。
WITH cte
AS (SELECT Row_number() OVER ( partition BY ID
ORDER BY CASE LOCATION WHEN 'in-house' THEN 0
WHEN 'outside' THEN 1 END,
DATE DESC) rn,
ID,
Date,
Location
FROM prod)
SELECT ID,
Date,
Location
FROM cte
WHERE rn = 1
注意我们不必使用case语句,但我希望映射是显式的。