是否可以将这两个左连接合并为一个?
我想不出任何方式
select left1.field1,
left2.field2
from masterTable left join (
select somefield,
field1,
row_number() over (partition by somefield orderby otherfield) as rowNum
from childTable
inner join masterTable
on masterTable.somefield = childTable.somefield
) as left1
on masterTable.somefield = left1.somefield
AND left1.rownum =1
left join (
select somefield,
max(field2) as field2
from childTable
inner join masterTable
on masterTable.somefield = childTable.somefield
where field3 = 1
group by somefield
) as left2
on masterTable.somefield = left2.somefield
答案 0 :(得分:1)
您可以使用max() over()
获取同一查询中每个某个字段的最大字段数。
select left1.field1,
left1.field2
from masterTable
left join
(select
somefield,field1
,row_number() over (partition by somefield orderby otherfield) as rowNum
,max(field2) over(partition by somefield) as field2
from childTable
inner join masterTable on masterTable.somefield = childTable.somefield) as left1
ON masterTable.somefield = left1.somefield
AND left1.rownum =1 AND field3 = 1
答案 1 :(得分:0)
请试试这个..
select left1.field1,
left1.field2
from masterTable
left join
(select
somefield,field1
,row_number() over (partition by somefield orderby otherfield) as rowNum
,max(field2) over(partition by somefield) as field2
from childTable
inner join masterTable on masterTable.somefield = childTable.somefield
group by somefield,field1
,row_number() over (partition by somefield orderby otherfield)
)
as left1
ON masterTable.somefield = left1.somefield
AND left1.rownum =1 AND field3 = 1
答案 2 :(得分:0)
试试这个,但没有数据和输出的样本我不能保证它能正常工作,它只是在猜测。
SELECT field1,
MAX(field2) AS field2
FROM (
SELECT ct.field1,
ct1.field2,
ROW_NUMBER() OVER (PARTITION BY ct.somefield ORDER BY ct.otherfield) as rn
FROM masterTable mt
INNER JOIN childTable ct
ON mt.somefield = ct.somefield
LEFT JOIN childTable ct1
ON mt.somefield = ct1.somefield AND ct1.field3 = 1
) as t
WHERE rn = 1
GROUP BY ct.field1