嗨,我不擅长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
答案 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;
使用这种方法,您可以使用复杂的表达式来拥有尽可能多的不同值。