sql语句中case_SQL中的CASE语句

sql语句中case

The case statement in SQL returns a value on a specified condition. We can use a Case statement in select queries along with Where, Order By and Group By clause. It can be used in Insert statement as well. In this article, we would explore CASE statement and its various use cases.

SQL中的case语句返回指定条件下的值。 我们可以在选择查询中使用Case语句以及Where,Order By和Group By子句。 也可以在Insert语句中使用它。 在本文中,我们将探讨CASE语句及其各种用例。

Suppose you have a table that stores the ProductID for all products in a mini-store. You want to get Productname for a particular ProductID.

假设您有一个表,该表在迷你商店中存储所有产品的ProductID。 您想要获取特定ProductID的Productname。

Look at the following example; We declared a variable @ProductID and specified value 1 for it. In Case statement, we defined conditions. Once a condition is satisfied, its corresponding value is returned.

看下面的例子; 我们声明了一个变量@ProductID并为其指定了值1。 在案例陈述中,我们定义了条件。 一旦满足条件,将返回其对应的值。

sql语句中case_SQL中的CASE语句_第1张图片

Similarly, if we change the condition in a Case statement in SQL, it returns appropriate expression. In the following example, we want to get Product name for ProductID 4.it does not satisfy Case statement condition; therefore, it gave output from Else expression.

同样,如果我们在SQL中的Case语句中更改条件,则它将返回适当的表达式。 在下面的示例中,我们想要获取ProductID 4的产品名称。它不满足Case语句条件; 因此,它给出了Else表达式的输出。

sql语句中case_SQL中的CASE语句_第2张图片

Let us explore a few examples of the Case statement in SQL. Before we proceed, create a sample table and insert few records in it.

让我们探讨一下SQL中Case语句的一些示例。 在继续之前,创建一个示例表并在其中插入一些记录。

USE [SQLShackDemo]
GO
CREATE TABLE dbo.Employee 
( 
EmployeeID INT IDENTITY PRIMARY KEY, 
EmployeeName VARCHAR(100) NOT NULL, 
Gender VARCHAR(1) NOT NULL, 
StateCode VARCHAR(20) NOT NULL, 
Salary money NOT NULL,
) 
GO
USE [SQLShackDemo]
GO
SET IDENTITY_INSERT [dbo].[Employee] ON 
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [StateCode], [Salary]) VALUES (201, N'Jerome', N'M', N'FL', 83000.0000)
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [StateCode], [Salary]) VALUES (202, N'Ray', N'M', N'AL', 88000.0000)
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [StateCode], [Salary]) VALUES (203, N'Stella', N'F', N'AL', 76000.0000)
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [StateCode], [Salary]) VALUES (204, N'Gilbert', N'M', N'Ar', 42000.0000)
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [StateCode], [Salary]) VALUES (205, N'Edward', N'M', N'FL', 93000.0000)
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [StateCode], [Salary]) VALUES (206, N'Ernest', N'F', N'Al', 64000.0000)
GO
INSERT [dbo].[E

你可能感兴趣的:(java,python,mysql,sql,数据库)