SQL 如何根据条件选择列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1368527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how do I select a column based on condition?
提问by Riz
I have a variable called @status which I set before this select statement:
我有一个名为 @status 的变量,我在这个 select 语句之前设置了它:
Select
ordr_num as num,
ordr_date as date,
ordr_ship_with as shipwith
From
order
where ordr_num = @ordrNum
I only want to select ordr_ship_with
column if @status <> 'Cancelled'
, otherwise I want to select null for shipwith. How do I accomplish this?
我只想选择ordr_ship_with
列 if @status <> 'Cancelled'
,否则我想为发货选择 null 。我该如何实现?
回答by Joel Coehoorn
SELECT ordr_num as num, ordr_date as date,
CASE WHEN @status<>'Cancelled' THEN ordr_ship_with ELSE NULL END as shipwith
FROM order
WHERE ordr_num = @ordrNum
回答by Raj More
Try this out
试试这个
Select
ordr_num as num,
ordr_date as date,
CASE
WHEN @Status <> 'Cancelled' THEN ordr_ship_with
ELSE NULL END
as shipwith
From order
where ordr_num = @ordrNum
Although I have a feeling that you STATUS is an actual column in the Order table. In that case, do this:
尽管我有一种感觉,您 STATUS 是 Order 表中的实际列。在这种情况下,请执行以下操作:
Select
ordr_num as num,
ordr_date as date,
CASE
WHEN Status <> 'Cancelled' THEN ordr_ship_with
ELSE NULL END
as shipwith
From order
where ordr_num = @ordrNum
回答by gbn
Select
ordr_num as num,
ordr_date as date,
CASE WHEN @status <> 'Cancelled' THEN ordr_ship_with ELSE NULL END as shipwith
From
order where ordr_num = @ordrNum
回答by Russell Steen
Try this
尝试这个
SELECT CASE
WHEN @status <> 'cancelled' THEN ordr_ship_with
ELSE null
END AS shipwith, ... other fields