sql - 如何优先从表中获取列
问题描述
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- 选择列值的优先级(速率 | 最大值 | 最小值):
- 如果列
rate
中TABLE C
有值,则不考虑TABLE B
==> 结果中的值TABLE C
- 如果列
rate
inTABLE C
isnull
但在TABLE B
==> 结果中具有值,则从TABLE B
解决方案
这是使用 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
添加您需要的任何排序。
推荐阅读
- spyder - 如何在 Spyder 中禁用菜单快捷方式?
- r - 如何使用正则表达式替换 '\U'?
- sql-server - FireDAC:KILL 命令不能在用户事务中使用
- performance - Julia 启动和运行文件的时间异常长
- c# - Microsoft.Azure.WebJobs.Host:错误索引方法“HttpExample”
- react-native - 从父选项卡打开深层链接不起作用
- c# - 第一人称和第三人称之间的相机切换。显示错误
- authentication - 在气流 2.1.4 中创建具有 LDAP 身份验证的用户
- microsoft-dynamics - 用于 React 的 MS-Dynamics 导出功能
- javascript - 在 Material-UI 中禁用表格分页