从嵌套在CASE中的SELECT返回多个值

时间:2011-07-27 14:11:04

标签: sql nested case

我正在尝试在单个列中返回多个值,这些值链接到位置编号(1到6),但只包含在每种情况下具有特定位置的那些值。基本上我要创建6列,每个位置1,并返回与该位置编号关联的所有结果值。我创建了6个嵌套Case语句来尝试获得这些结果:

(CASE WHEN tbl_TestWells.well_result <> NULL
THEN 
(SELECT tbl_TestWells.well_result
FROM tbl_TestWells
WHERE tbl_TestWells.Well_Index = 1)
ELSE NULL END) AS  Well_1_Graded_Result,

问题是它们只按照设置的方式返回NULL值。如果我拿出案例然后我得到错误消息“子查询返回超过1的值。当子查询跟随=,!=,&lt;,&lt; =,&gt;,&gt; =或子查询时,这是不允许的用作表达。“

编辑:完整的代码是视图的一部分,所以我把它简化为相关的

SELECT DISTINCT
--Other Columns being selected

(CASE WHEN tbl_TestWells.well_result <> NULL
THEN 
(SELECT tbl_TestWells.well_result
FROM tbl_TestWells
WHERE tbl_TestWells.Well_Index = 1)
ELSE NULL END) AS  Well_1_Graded_Result,

--The other five well results are set up in the exact same format as above, just replacing 1 with the corresponding number

FROM tbl_TestCartridges

JOIN tbl_Tests ON
tbl_Tests.test_uid = tbl_TestCartridges.test_uid

JOIN tbl_Programs ON
tbl_Programs.program_uid = tbl_Tests.program_uid

JOIN tbl_Cartridges ON
tbl_Cartridges.system_uid = tbl_Programs.system_uid

JOIN tbl_TestWells ON
tbl_TestWells.test_cartridge_uid = tbl_TestCartridges.test_cartridge_uid

JOIN tbl_TestSamples ON
tbl_TestSamples.test_well_uid = tbl_TestWells.test_well_uid 

ORDER BY tbl_TestCartridges.barcode

; 

3 个答案:

答案 0 :(得分:1)

CASE语句不能用于导致6行代替一行。您需要在查询的JOIN中构建“1行或多行”逻辑,而不是CASE语句。

包括您的完整查询和架构,以及您要实现的目标的解释。

答案 1 :(得分:0)

检查NULL值时,不能使用逻辑运算符。 NULL表示未知,因此1 = NULL?编号是1&lt;&gt;空值?不,因为在这种情况下NULL 可能为1 - 我们不知道,它的未知。

相反,您需要使用IS NULLIS NOT NULL进行NULL检查和比较。

所以,它看起来像这样:

(CASE WHEN tbl_TestWells.well_result IS NOT NULL THEN ...

答案 2 :(得分:0)

我猜你有几个({6})行tbl_TestWells.Well_Index = 1, 2, 3...,你想将这些结果收集到一行?

如果是,您需要以下内容:

SELECT
    MIN( CASE WHEN tbl_TestWells.well_result IS NOT NULL
                   AND tbl_TestWells.Well_Index = 1
              THEN tbl_TestWells.well_result
         END
       ) AS  Well_1_Graded_Result
  , MIN( CASE WHEN tbl_TestWells.well_result IS NOT NULL
                  AND tbl_TestWells.Well_Index = 2
              THEN tbl_TestWells.well_result
         END 
       ) AS  Well_2_Graded_Result
  , ...
FROM 
    ...
GROUP BY
         ?                         --- what do these (6) rows have in common?
ORDER BY
         tbl_TestCartridges.barcode