0

我想选择两个绑定到表的值,如果它们不存在,则填充一个空值。但是,我只想要每条记录一行。如果我运行下面的查询,CASE 语句会创建重复的行。

SELECT DISTINCT YT.TITLE, YT.DETAILS,
CASE WHEN XT.ACOLUMN = 'CATEGORY' THEN XT.BCOLUMN END AS CATEGORY,
CASE WHEN XT.ACOLUMN = 'DIVISION' THEN XT.BCOLUMN END AS DIVISION 
FROM DB.YTABLE YT
LEFT OUTER JOIN DB.XTABLE XT
ON YT.ID_NUM = XT.ID_NUM

我想要的数据:

标题Example1、DetailsExample1、Category1、Division1

TitleExample2, DetailsExample2, null, Division2

我得到的数据:

TitleExample1,DetailsExample1,Category1,空

TitleExample1, DetailsExample1, null, Division1

TitleExample1,DetailsExample1,空,空

TitleExample2, DetailsExample2, null, Division2

TitleExample2,DetailsExample2,空,空

我还尝试对同一个表使用多个表身份进行连接:

SELECT DISTINCT YT.TITLE, YT.DETAILS, XT1.BCOLUMN AS CATEGORY1, 
       XT2.BCOLUMN AS DIVISION 
LEFT OUTER JOIN DB.XTABLE XT1
ON YT.ID_NUM = XT.ID_NUM
LEFT OUTER JOIN DB.XTABLE XT2
ON YT.ID_NUM = XT.ID_NUM
 WHERE XT1.ACOLUMN = 'CATEGORY' AND
 XT2.ACOLUMN = 'DIVISION' 

如果同时填充了类别值和部门值,这将很有效。但是,如果标题和详细信息记录没有关联的类别或部门,则查询不会选择该记录。

我想要的数据:

标题Example1、DetailsExample1、Category1、Division1

TitleExample2, DetailsExample2, null, Division2

我得到的数据:

标题Example1、DetailsExample1、Category1、Division1

4

2 回答 2

1

您的第二种方法更好,但您必须在 OUTER JOIN 的 ON 语句中添加您的条件

SELECT DISTINCT YT.TITLE, YT.DETAILS, XT1.BCOLUMN AS CATEGORY1, XT2.BCOLUMN AS DIVISION 
FROM DB.YTABLE YT
LEFT OUTER JOIN DB.XTABLE XT1 ON (YT.ID_NUM = XT1.ID_NUM AND XT1.ACOLUMN = 'CATEGORY')
LEFT OUTER JOIN DB.XTABLE XT2 ON (YT.ID_NUM = XT2.ID_NUM AND XT2.ACOLUMN = 'DIVISION')
于 2013-05-03T14:39:23.037 回答
0
SELECT YT.TITLE, YT.DETAILS,
Min(CASE WHEN XT.ACOLUMN = 'CATEGORY' THEN XT.BCOLUMN END) AS CATEGORY,
Min(CASE WHEN XT.ACOLUMN = 'DIVISION' THEN XT.BCOLUMN END) AS DIVISION 
FROM DB.YTABLE YT
LEFT OUTER JOIN DB.XTABLE XT
ON YT.ID_NUM = XT.ID_NUM
Group By YT.TITLE, YT.DETAILS
于 2013-05-03T14:27:20.920 回答