SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN "The quantity is greater than 30"
WHEN Quantity = 30 THEN "The quantity is 30"
ELSE "The quantity is under 30"
END AS QuantityText
FROM OrderDetails;
Using SQL CASE is just like normal If / Else statements. In the below query, if obsolete value = 'N' or if InStock value = 'Y' then the output will be 1. Otherwise the output will be 0. Then we put that 0 or 1 value under the Salable Column.
SELECT
CASE
WHEN obsolete = 'N' OR InStock = 'Y'
THEN 1
ELSE 0
END AS Salable
, *
FROM PRODUCT
INSERT INTO customers (last_name, first_name, city)
SELECT 'Doe', 'John', 'Chicago' FROM dual
WHERE NOT EXISTS
(SELECT '1' from customers
where last_name = 'Doe'
and first_name = 'John'
and city = 'Chicago');
CASE orweb2.dbo.Inventory.RegulatingAgencyName
WHEN 'Region 1'
THEN orweb2.dbo.CountyStateAgContactInfo.ContactState
WHEN 'Region 2'
THEN orweb2.dbo.CountyStateAgContactInfo.ContactState
WHEN 'Region 3'
THEN orweb2.dbo.CountyStateAgContactInfo.ContactState
WHEN 'DEPT OF AGRICULTURE'
THEN orweb2.dbo.CountyStateAgContactInfo.ContactAg
ELSE (
CASE orweb2.dbo.CountyStateAgContactInfo.IsContract
WHEN 1
THEN orweb2.dbo.CountyStateAgContactInfo.ContactCounty
ELSE orweb2.dbo.CountyStateAgContactInfo.ContactState
END
)
END AS [County Contact Name]
30条答案
按热度按时间avkwfej41#
kgsdhlau2#
为了完整起见,我想补充一句,SQL使用三值逻辑。该表达式为:
可以产生三种截然不同的结果:
例如,如果一个产品过时了,但你不知道产品是否有库存,那么你就不知道产品是否畅销。您可以按如下方式编写此三值逻辑:
一旦弄清楚了它的工作原理,就可以通过决定NULL的行为将三个结果转换为两个结果。例如,这会将Null视为不可销售:
g0czyy6m3#
pgvzfuti4#
我喜欢使用CASE语句,但问题要求在SQL Select中使用IF语句。我过去用过的是:
它类似于Excel或Sheets IF语句,其中条件后跟TRUE条件,然后是FALSE条件:
此外,您可以嵌套if语句(但使用时应使用case:-)
(注:此功能适用于MySQL Workbench,但可能不适用于其他平台)
2vuwiymt5#
大概是这样的:
jk9hmnmh6#
Using SQL CASE is just like normal If / Else statements. In the below query, if obsolete value = 'N' or if InStock value = 'Y' then the output will be 1. Otherwise the output will be 0. Then we put that 0 or 1 value under the Salable Column.
n3ipq98p7#
Question:
ANSI:
Using aliases --
p
in this case -- will help prevent issues.2guxujil8#
nbysray59#
ghhkc1vu10#
For those who uses SQL Server 2012, IIF is a feature that has been added and works as an alternative to Case statements.
ttcibm8c11#
You can have two choices for this to actually implement:
Select Case
:bzzcjhmw12#
f3temu5u13#
作为
CASE
语句的替代解决方案,可以使用表驱动方法:结果:
evrscar214#
如果您是第一次将结果插入到表中,而不是将结果从一个表传输到另一个表,则这在Oracle 11.2g中有效:
wwodge7n15#
这不是一个答案,只是我工作的地方使用的案例语句的一个例子。它有一个嵌套的CASE语句。现在你知道为什么我的眼睛是交叉的了。