SQL SELECT一个存在的值,否则多次填充一个空值

时间:2013-05-03 14:25:03

标签: sql select case

我想选择两个与表绑定的值,如果它们不存在,则填充空值。但是,我只希望每条记录有一行。如果我运行下面的查询,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

我想要的数据:

  

TitleExample1,DetailsExample1,Category1,Division1

     

TitleExample2,DetailsExample2,null,Division2

我得到的数据:

  

TitleExample1,DetailsExample1,Category1,null

     

TitleExample1,DetailsExample1,null,Division1

     

TitleExample1,DetailsExample1,null,null

     

TitleExample2,DetailsExample2,null,Division2

     

TitleExample2,DetailsExample2,null,null

我还尝试使用同一个表的多个表标识进行连接:

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' 

如果填充了类别和除法值,则此方法很有效。但是,如果标题和详细信息记录没有关联的类别或分区,则查询将不会选择该记录。

我想要的数据:

  

TitleExample1,DetailsExample1,Category1,Division1

     

TitleExample2,DetailsExample2,null,Division2

我得到的数据:

  

TitleExample1,DetailsExample1,Category1,Division1

2 个答案:

答案 0 :(得分: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')

答案 1 :(得分: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