我现在被卡住了......
我有4种类型的发票需要不同的选定字段......
现在我正在尝试类似......
SELECT
CASE WHEN EXISTS (SELECT * FROM invoices WHERE type ='inv') THEN
(SELECT a,b,c FROM invoices)
WHEN EXISTS (SELECT * FROM invoices WHERE type ='credit') THEN
(SELECT d,e,f FROM invoices)
end
from invoices
这无法正常工作......
我得到了:
Msg 116,Level 16,State 1,Line 6
当未使用EXISTS引入子查询时,只能在选择列表中指定一个表达式。
有没有人知道如何处理这样的事情?我完全失去了......
答案 0 :(得分:4)
由于CASE WHEN指令,您不能放置子查询。试试,其中之一:
SELECT case [type]
when 'inv' then a
when 'credit' then d
else 0
end
,
case [type]
when 'inv' then b
when 'credit' then e
else 0
end
,
case [type]
when 'inv' then c
when 'credit' then f
else 0
end
from invoices
或
select a, b, c
from invoices
where [type] = 'inv'
union
select d, e, f
from invoices
where [type] = 'credit'
答案 1 :(得分:1)
我认为这是你想要的,当type ='inv'时列a,b和c,或者当type ='credit'时列d,e,f:
SELECT a,b,c FROM invoices WHERE type ='inv'
UNION ALL
SELECT d,e,f FROM invoices WHERE type ='credit'
答案 2 :(得分:0)
您还可以返回忽略所有字段或将记录的无效字段设置为空。
SELECT
a=CASE WHEN Type='inv' THEN a ELSE NULL END,
b=CASE WHEN Type='inv' THEN b ELSE NULL END,
c=CASE WHEN Type='inv' THEN c ELSE NULL END,
d=CASE WHEN Type='credit' THEN d ELSE NULL END,
e=CASE WHEN Type='credit' THEN e ELSE NULL END,
f=CASE WHEN Type='credit' THEN f ELSE NULL END,
FROM
invoices
答案 3 :(得分:0)
尝试这样:
IF EXISTS (SELECT * FROM invoices WHERE type ='inv')
(SELECT a,b,c FROM invoices)
ELSE IF EXISTS (SELECT * FROM invoices WHERE type ='credit')
(SELECT d,e,f FROM invoices)