如何在 SQL 中组合空值和 varchar 值?
How to combine null values and varchar values in SQL?
我正在处理一个特别烦人的数据集。我刚刚设法让数据与预期的一致,但现在我在处理 merging/combining 一些行时遇到了问题,因此我有一个更整洁的 table。为了帮助您理解这就是我得到的:
order_id
aso_flag
dpo_flag
tcv
ops
penalty_charge
4540
N
Y
1.7
0
0
4540
1.4
0
这就是我想要的:
order_id
aso_flag
dpo_flag
tcv
ops
penalty_charge
4540
N
Y
1.7
1.4
0
这是我当前查询的底部:
SELECT
order_id
,NULL AS aso_flag
,dpo_flag
,tcv
,0 AS ops
,0 AS penalty_charge
FROM CO
UNION ALL
SELECT
order_id
,aso_flag
,null AS dpo_flag
,0 AS tcv
,ops
,penalty_charge
FROM OPS
使用的初始 tables 不完全相互镜像(缺少 order_ids)并且对它们的完全连接似乎非常非常慢。如有任何建议,我们将不胜感激!
从您的 Union
派生 Table 然后 group by
和 max
SELECT
order_id,
MAX(aso_flag) aso_flag,
MAX(dpo_flag) dpo_flag,
MAX(tcv) tcv,
MAX(ops) ops,
MAX(penalty_charge) penalty_charge
FROM (SELECT
order_id,
NULL AS aso_flag,
dpo_flag,
tcv,
0 AS ops,
0 AS penalty_charge
FROM CO
UNION ALL
SELECT
order_id,
aso_flag,
NULL AS dpo_flag,
0 AS tcv,
ops,
penalty_charge
FROM OPS) x
GROUP BY order_id
我正在处理一个特别烦人的数据集。我刚刚设法让数据与预期的一致,但现在我在处理 merging/combining 一些行时遇到了问题,因此我有一个更整洁的 table。为了帮助您理解这就是我得到的:
order_id | aso_flag | dpo_flag | tcv | ops | penalty_charge |
---|---|---|---|---|---|
4540 | N | Y | 1.7 | 0 | 0 |
4540 | 1.4 | 0 |
这就是我想要的:
order_id | aso_flag | dpo_flag | tcv | ops | penalty_charge |
---|---|---|---|---|---|
4540 | N | Y | 1.7 | 1.4 | 0 |
这是我当前查询的底部:
SELECT
order_id
,NULL AS aso_flag
,dpo_flag
,tcv
,0 AS ops
,0 AS penalty_charge
FROM CO
UNION ALL
SELECT
order_id
,aso_flag
,null AS dpo_flag
,0 AS tcv
,ops
,penalty_charge
FROM OPS
使用的初始 tables 不完全相互镜像(缺少 order_ids)并且对它们的完全连接似乎非常非常慢。如有任何建议,我们将不胜感激!
从您的 Union
派生 Table 然后 group by
和 max
SELECT
order_id,
MAX(aso_flag) aso_flag,
MAX(dpo_flag) dpo_flag,
MAX(tcv) tcv,
MAX(ops) ops,
MAX(penalty_charge) penalty_charge
FROM (SELECT
order_id,
NULL AS aso_flag,
dpo_flag,
tcv,
0 AS ops,
0 AS penalty_charge
FROM CO
UNION ALL
SELECT
order_id,
aso_flag,
NULL AS dpo_flag,
0 AS tcv,
ops,
penalty_charge
FROM OPS) x
GROUP BY order_id