SQL CASE在select语句内设置为多个变量

时间:2018-08-29 09:12:09

标签: sql case

嗨,我不擅长sql,我一直在想这是否可行或解决方案是否可行:

从这里:

SELECT name,
     (CASE
        WHEN @idparam =  tmp.id THEN
            tmp.total_number_subjects
        ELSE
            0
      END) AS TOTAL_SUBJECT_NUMBER,
      (CASE
        WHEN @idparam =  tmp.id THEN
            tmp.total_number_subjects
        ELSE
            0
      END) AS COPY_TOTAL_SUBJECT_NUMBER
      FROM #table tmp

看起来像这样:

SELECT name,
     (CASE
        WHEN @idparam =  tmp.id THEN
            tmp.total_number_subjects
        ELSE
            0
      END) AS (TOTAL_SUBJECT_NUMBER,COPY_TOTAL_SUBJECT_NUMBER)
      FROM #table tmp

3 个答案:

答案 0 :(得分:0)

您可以像下面的示例一样使用嵌套选择进行操作

select Name
     , x as TOTAL_SUBJECT_NUMBER
     , x as COPY_TOTAL_SUBJECT_NUMBER 
  from (
    SELECT name,
          (CASE
             WHEN @idparam =  tmp.id THEN
                 tmp.total_number_subjects
           ELSE
              0
           END) AS x
      FROM #table tmp
)

答案 1 :(得分:0)

您似乎想拒绝case表达式的重复:

SELECT tmp.Name, t.subject_number AS TOTAL_SUBJECT_NUMBER, 
       t.subject_number AS COPY_TOTAL_SUBJECT_NUMBER
FROM #table tmp CROSS APPLY
     ( VALUES (CASE WHEN @idparam = tmp.id 
                    THEN tmp.total_number_subjects ELSE 0
               END)
     ) t (subject_number);

答案 2 :(得分:0)

如果愿意,可以消除case并使用以下代码:

SELECT name,
       s.TOTAL_SUBJECT_NUMBER,
       s.COPY_TOTAL_SUBJECT_NUMBER
FROM #table t CROSS APPLY
     (SELECT tmp.total_number_subjects as TOTAL_SUBJECT_NUMBER, tmp.total_number_subjects as COPY_TOTAL_SUBJECT_NUMBER
      WHERE @idparam = tmp.id 
      UNION ALL
      SELECT tmp.total_number_subjects as TOTAL_SUBJECT_NUMBER, tmp.total_number_subjects as COPY_TOTAL_SUBJECT_NUMBER
      WHERE @idparam <> tmp.id   -- might need to take NULL into account
     ) s;

使用这种方法,您可以使用复杂的表达式来拥有尽可能多的不同值。