我在SQL中遇到查询问题。我的查询是这样的:
SELECT t.id, t.attribute, t.name, t.date
FROM (
SELECT *
FROM table1
WHERE ...
UNION
SELECT *
FROM table2
WHERE
UNION
...) t
WHERE ...
GROUP BY t.attribute
我想要的是获取每个属性的最新日期的所有行(日期可以为null,然后是最新的)。 我知道我可以创建一个临时表,但如果可能的话我想避免它。 我也希望不再在WHERE和JOIN中再次嵌套FROM的相同查询。 有什么办法吗?
谢谢!
答案 0 :(得分:0)
这是使用CTE(公用表表达式)执行此操作的一种方法:
{{1}}
答案 1 :(得分:0)
使用modern SQL,您可以使用窗口函数:
SELECT t2.id, t2.attribute, t2.name, t2.date
FROM (
SELECT t1.id, t1.attribute, t1.name, t1.date,
row_number() over (partition by t1.attribute order by t1.date desc) as rn
FROM (
SELECT *
FROM table1
WHERE ...
UNION
SELECT *
FROM table2
WHERE ...
UNION
...
) t1
) t2
where rn = 1;
或者使用公用表表达式来避免派生表的嵌套:
with data as (
SELECT *
FROM table1
WHERE ...
UNION
SELECT *
FROM table2
WHERE ...
UNION
), numbered as (
SELECT id, attribute, name, date,
row_number() over (partition by t1.attribute order by t1.date desc) as rn
FROM data
)
SELECT id, attribute, name, date
from numbered
where rn = 1;