首页 > 解决方案 > 如何优先从表中获取列

问题描述

SELECT我有三个表,它们对语句中的选择列具有优先权。

假设表 A 有一些列,例如:

表 A:

A_ID     |name
---------|-------
1        |name1

表 B:

purchase |A_ID |type | market | group | rate    |   max  |   min
---------|-----|-----|--------|-------|---------|--------|---------
    1    |  1  |  1  |   1    |   1   |  0.12   |  1000  |   500
    1    |  1  |  2  |   1    |   1   |  0.3    |  2000  |   1500
    0    |  1  |  3  |   1    |   1   |  0.2    |  5000  |   800
    0    |  1  |  4  |   1    |   1   |  0.6    |  8000  |   2800
    0    |  1  |  6  |   1    |   1   |  0.7    |  null  |   2800

表 C:

purchase |A_ID |type | market | group | rate    |   max  |   min
---------|-----|-----|--------|-------|---------|--------|---------
    1    |  1  |  1  |   1    | null  |  0.2    |  null  |   null
    1    |  1  |  2  |   1    | null  |  null   |  5000  |   3000
    0    |  1  |  3  |   1    | null  |  0.5    |  3000  |   1000
    0    |  1  |  5  |   1    | null  |  0.4    |  3800  |   2000
    0    |  1  |  6  |   1    | null  |  null   |  null  |   3000

期望的结果:

purchase |A_ID |type | market | rate    |   max  |   min
---------|-----|-----|--------|---------|--------|---------
    1    |  1  |  1  |   1    |  0.2    |  1000  |   500
    1    |  1  |  2  |   1    |  0.3    |  5000  |   3000
    0    |  1  |  3  |   1    |  0.5    |  3000  |   1000
    0    |  1  |  5  |   1    |  0.4    |  3800  |   2000
    0    |  1  |  4  |   1    |  0.6    |  8000  |   2800
    0    |  1  |  6  |   1    |  0.7    |  null  |   3000

从列中获取值的规则:

1-Table C比 具有更高的优先级Table B,这意味着如果它们在同一列中都有值,则从 中提取结果Table C,除非值为 null

2-结果可以GROUP BY打开purchase, type, market

3- Result Has FULL JOIN,这意味着如果一行在另一侧有等效行,则使用优先级获取值,如果不是整行进入结果

4- 选择列值的优先级(速率 | 最大值 | 最小值):

标签: sqloracle

解决方案


这是使用 sql server 语法,我相信您可以根据需要进行更改:

首先设置样本数据:

declare @a table(purchase int,A_ID int,[type] int,market int,[group] int,rate decimal(5,2),[max] int,[min] int)
insert @a values (1,1,1,1,1,0.12,1000,500)
,(1,1,2,1,1,0.3,2000,1500)
,(0,1,3,1,1,0.2,5000,800)
,(0,1,4,1,1,0.6,8000,2800)
,(0,1,6,1,1,0.7,null,2800)

declare @b table(purchase int,A_ID int,[type] int,market int,[group] int,rate decimal(5,2),[max] int,[min] int)
insert @b values 
(1,1,1,1,null,0.2,null,null)
,(1,1,2,1,null,null,5000,3000)
,(0,1,3,1,null,0.5,3000,1000)
,(0,1,5,1,null,0.4,3800,2000)
,(0,1,6,1,null,null,null,3000)

然后查询:

select coalesce(b.purchase,a.purchase) purchase,
    coalesce(b.A_ID,a.A_ID) A_ID,
    coalesce(b.[type],a.[type]) [type],
    coalesce(b.market,a.market) market,
    coalesce(b.rate,a.rate) rate,
    coalesce(b.[max],a.[max]) [max],
    coalesce(b.[min],a.[min]) [min]
from @a a
full outer join @b b on b.purchase=a.purchase and b.[type]=a.[type] and b.market=a.market
order by rate

添加您需要的任何排序。


推荐阅读