SQL Server 2008 R2:从列中获取第一个非空值
Posted
技术标签:
【中文标题】SQL Server 2008 R2:从列中获取第一个非空值【英文标题】:SQL Server 2008 R2: Get first not null values from column 【发布时间】:2017-12-04 05:49:23 【问题描述】:我有以下表格来显示预期结果。
表格:
CREATE TABLE Family
(
ID int,
Name varchar(20),
Gender char(1)
);
INSERT INTO Family VALUES
(1,'Ram','M'),
(2,'Suraj','M'),
(3,'Sunitha','F'),
(4,'Deepika','F'),
(5,'Minakshi','F'),
(6,'Somu','M');
CREATE TABLE Child_parent
(
Child_ID int,
Parent_ID int
);
INSERT INTO Child_parent VALUES
(1,2),
(1,3),
(4,5),
(4,6);
预期结果:
Child_ID ChildName FatherName MotherName
-----------------------------------------------
1 Ram Suraj Sunitha
4 Deepika Somu Minakshi
我的尝试:
SELECT cp.Child_ID,
f1.Name as ChildName,
CASE WHEN f2.Gender = 'M' THEN f2.Name END FatherName,
CASE WHEN f2.Gender = 'F' THEN f2.Name END MotherName
FROM Child_parent cp
LEFT JOIN Family f1
ON cp.Child_ID = f1.ID
LEFT JOIN Family f2
ON cp.Parent_ID = f2.ID
但是得到的结果显示:
Child_ID ChildName FatherName MotherName
----------------------------------------------
1 Ram Suraj NULL
1 Ram NULL Sunitha
4 Deepika NULL Minakshi
4 Deepika Somu NULL
【问题讨论】:
【参考方案1】:试试这个
SELECT cp.Child_ID,
f1.Name as ChildName,
max(CASE WHEN f2.Gender = 'M' THEN f2.Name END) FatherName,
max(CASE WHEN f2.Gender = 'F' THEN f2.Name END) MotherName
FROM Child_parent cp
LEFT JOIN Family f1
ON cp.Child_ID = f1.ID
LEFT JOIN Family f2
ON cp.Parent_ID = f2.ID
group by cp.Child_ID,
f1.Name
order by cp.Child_ID
【讨论】:
【参考方案2】:这是使用单个 JOIN
的替代解决方案。
SELECT CP.Child_ID,
MAX(CASE WHEN CP.Parent_ID <> F.ID THEN F.Name END) ChildName,
MAX(CASE WHEN CP.Parent_ID = F.ID AND F.Gender ='M' THEN F.Name END) FatherName,
MAX(CASE WHEN CP.Parent_ID = F.ID AND F.Gender ='F' THEN F.Name END) MotherName
FROM
Child_parent CP
LEFT JOIN Family F ON CP.Parent_ID = F.ID OR CP.Child_ID = F.ID
GROUP BY
Child_ID
【讨论】:
以上是关于SQL Server 2008 R2:从列中获取第一个非空值的主要内容,如果未能解决你的问题,请参考以下文章
获取每个月的第一个日期 SQL Server 2008 R2
根据 SQL Server 2008 R2 中特定列中的模式更改对行进行分组
在 SQL Server 2008 R2 事务复制中筛选列数据