仅在第一行左联接

kse8i1jr  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(334)

我有以下示例查询:

WITH a As
(
SELECT '2020-04-01' as date,'test123' as id,'abc' as foo,10 as purchases  Union all
SELECT '2020-04-01', 'test123', 'abc', 0   Union all
SELECT '2020-04-01', 'test123', 'abc', 0
),
b as
(
SELECT '2020-04-01' as date,'test123' as id,'abc' as foo,50 as budget
)
select
a.date,a.id,a.foo,a.purchases,budget
from a
LEFT JOIN b
ON
concat(a.date,a.id)=concat(b.date,b.id)

我想要以下输出

Row date,id,foo,purchases,budget    
1   2020-04-01,test123,abc,10,50
2   2020-04-01,test123,abc,0,null
3   2020-04-01,test123,abc,0,null

我读了很多关于类似主题的问题,但我没能使它起作用。

fd3cxomn

fd3cxomn1#

你可以用 row_number() :

select a.date, a.id, a.foo, a.purchases,
       (case when a.seqnum = 1 then b.budget end) as budget
from (seleect a.*, row_number() over (partition by date, id order by purchases desc) as seqnum
      from a 
     ) a
     b
     using (date, id);
px9o7tmv

px9o7tmv2#

在b inner查询中,将以下内容添加到所选列:
行号()在(按日期划分,按采购说明排序)上作为sequencenumber
然后在左边的连接中添加“and b.sequencenumber=1”
如果您真的对所有内容进行硬编码,而不是从实际表中进行选择,则可能是:

WITH a As
(
SELECT '2020-04-01' as date,'test123' as id,'abc' as foo,10 as purchases  Union all
SELECT '2020-04-01', 'test123', 'abc', 0   Union all
SELECT '2020-04-01', 'test123', 'abc', 0
),
b as
(
SELECT '2020-04-01' as date,'test123' as id,'abc' as foo,50 as budget
)
select
a.date,a.id,a.foo,a.purchases,budget
from a
LEFT JOIN b
ON a.date = b.date
    AND a.id = b.id
    AND a.purchases > 0

否则,如果在内部“b”查询中有一个表。然后是这样的:

WITH a As
(
SELECT '2020-04-01' as date,'test123' as id,'abc' as foo,10 as purchases  Union all
SELECT '2020-04-01', 'test123', 'abc', 0   Union all
SELECT '2020-04-01', 'test123', 'abc', 0
),
b as
(
SELECT '2020-04-01' as date,'test123' as id,'abc' as foo,50 as budget,
  ROW_NUMBER() OVER(PARTITION BY date ORDER BY Id) SequenceNumber
)
select
a.date,a.id,a.foo,a.purchases,budget
from a
LEFT JOIN b
ON a.date = b.date
    AND a.id = b.id
    AND b.SequenceNumber = 1

相关问题