【发布时间】:2020-05-20 08:08:46
【问题描述】:
桌车:
id serial size batch
--------------------------
1 x99 Large NULL
2 x99 Small Q
3 x99 Med NULL
4 x99 Large K
使用表代码分配连接两次:
Id serial size batch code precedence
-----------------------------------------------
1 x99 Large NULL 5000 1
2 x99 NULL K 3000 2
3 x99 NULL Q 2000 3
4 x99 NULL NULL 500 4
使用以下内容:
select
c.*,
coalesce(ca1.code, ca2.code) as code,
min(coalesce(ca1.precedence, ca2.precedence)) as precedence
from
cars c
left join
codeassignment ca1 on ca1.serial = c.serial
and (ca1.size = c.size or ca1.batch = c.batch)
left join
codeassignment ca2 on ca2.serial = c.serial
and ca1.size is null and ca2.size is null
and ca1.batch is null and ca2.batch is null
group by
c.id, c.serial, c.size, c.batch, ca1.code, ca2.code
但它会导致 'Large' 和批次 'K' 的匹配出现两次:
id serial size batch code precedence
----------------------------------------------
1 x99 Large A 5000 1
2 x99 Small Q 2000 3
3 x99 Med P 500 4
4 x99 Large K 3000 2
4 x99 Large K 5000 1
我想选择所有上述行,但对于最后两行,只有优先级最低的行(这就是我尝试min(precedence) 的原因),但我认为 group by 正确执行此操作是错误的。所以基本上serial、size和batch相同的地方应该只有一行。
这是一个小提琴:
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=47700d67170a7beb39bfc523ffdfbcfc
【问题讨论】:
标签: sql sql-server