我使用左外连接在SQL中加入了两个表(见下文)。
是否可以用其他数据填充空单元格?
(来自小提琴)
CREATE TABLE Data1
(cost_type nvarchar(10), contract nvarchar(10))
;
INSERT INTO Data1
(cost_type, contract)
VALUES
('LABR', 'contract1'),
('EQP', ''),
('RST', 'contract1')
;
CREATE TABLE data2
(cost_type nvarchar(10), contract nvarchar(10), Name nvarchar(max))
;
INSERT INTO data2
(cost_type,contract,Name)
VALUES
('LABR','contract1','John'),
('MAT','contract1','John'),
('EQP','','')
;
当前正在运行的查询:
select * from data1 dt1
left outer join data2 dt2 on dt1.cost_type=dt2.cost_type
我需要的结果如下:
COST_TYPE CONTRACT NAME
LABR, contract1, John
EQP, contract1, John
RST, contract1, John
此结果基于查找CONTRACT列的最常用值并使用该值替换所有空值。我需要为NAME列做同样的事情。
答案 0 :(得分:6)
编辑:当您在上面的评论中明确表示您希望使用最常用的合同/名称填充的值时,查询并不是太复杂而无法编写; CTE用于查找每个最常用的合同/名称,以及用CTE值替换空值的查询;
WITH most_used_contract AS (
SELECT TOP 1 contract FROM Data1
WHERE contract IS NOT NULL
GROUP BY contract
ORDER BY COUNT(*) DESC
), most_used_name AS (
SELECT TOP 1 name FROM Data2
WHERE name IS NOT NULL
GROUP BY name
ORDER BY COUNT(*) DESC
)
SELECT data1.cost_type,
CASE WHEN data1.contract IS NULL OR data1.contract = ''
THEN muc.contract
ELSE data1.contract END contract,
CASE WHEN data2.name IS NULL OR data2.name = ''
THEN mun.name
ELSE data2.name END name
FROM data1
LEFT JOIN data2 ON data1.cost_type=data2.cost_type
LEFT JOIN most_used_contract muc ON 1=1
LEFT JOIN most_used_name mun ON 1=1