sql语句 case_使用SQL Case语句查询数据

sql语句 case

The Case statement in SQL is mostly used in a case with equality expressions. The SQL Case statement is usually inside of a Select list to alter the output. What it does is evaluates a list of conditions and returns one of the multiple possible result expressions.

SQL中的Case语句主要用于带有相等表达式的case中。 SQL Case语句通常位于Select列表中,以更改输出。 它的作用是评估条件列表,并返回多个可能的结果表达式之一。

For instance, let’s see how we can reference the “AdventureWorks2012” database and show an example of a SQL Case statement.

例如,让我们看看如何引用“ AdventureWorks2012”数据库并显示一个SQL Case语句的示例。

We are going to take the “Gender” field which is only a character field. So, if we go to our sample database, tables, inside the “Employee” table there’s a column called “Gender” which is nchar data type. Right above is the “MaritalStatus” which is also nchar data type, meaning that those two have only one character:

我们将采用“性别”字段,它只是一个字符字段。 因此,如果我们转到示例数据库表,在“雇员”表内有一个名为“性别”的列,它是nchar数据类型。 右上方是“婚姻状况”,也是nchar数据类型,这意味着这两个只有一个字符:

Employee table in Object Explorer

So, if we want to output this to change the display of marital status and gender categories to make them more understandable consider the following query using a SQL Case statement:

因此,如果我们要输出此信息以更改婚姻状况和性别类别的显示,以使其更易理解,请考虑使用SQL Case语句进行以下查询:

USE AdventureWorks2012;
GO
SELECT p.FirstName,
       p.LastName,
       CASE e.Gender
           WHEN 'F'
           THEN 'Female'
           WHEN 'M'
           THEN 'Male'
           ELSE 'Unknown'
       END AS GenderDescription,
       MaritalStatusDescription = CASE MaritalStatus
                                      WHEN 'S'
                                      THEN 'Single'
                                      WHEN 'M'
                                      THEN 'Married'
                                      ELSE 'Unknown'
                                  END
FROM HumanResources.Employee AS e
     JOIN Person.Person AS p ON e.BusinessEntityID = p.BusinessEntityID;
GO

This is a great equality expression case statement in SQL. What it basically means is that we can do Case followed by the field name and then we can have all case expressions. In this particular case, whenever “Gender” equals “F” then it’s going to output “Female” and when it equals “M” then it’s going to output “Male”. Also, if it’s neither of those it’s going to output “Unknown”. Furthermore, we’re aliasing the name of the column as “GenderDescription”. Another way to do aliases is to put the name of the alias first followed by equals SQL Case on “MaritalStatus” as in the example above.

这是SQL中的一个很棒的相等表达式大小写语句。 它的基本含义是,我们可以先进行Case后跟字段名,然后才能拥有所有case表达式。 在这种情况下,每当“性别”等于“ F”时,它将输出“女性”;当其等于“ M”时,它将输出“男性”。 另外,如果两者都不是,则将输出“未知”。 此外,我们将列名别名为“ GenderDescription”。 进行别名的另一种方法是,首先将别名的名称放在“ MaritalStatus”上,后跟等号SQL Case,如上例所示。

So, if we now execute our query with this SQL Case statement it will fetch that information and output it appropriately:

因此,如果现在使用此SQL Case语句执行查询,它将获取该信息并适当地输出它:

Results of a query that displays marital status and gender categories

It’s not seen in this example because all the fields match arguments but the Case statement in SQL supports an optional Else argument. This means that you’d have seen the “Unknown” output as well if the character was anything else than stated in the When clause.

在本示例中没有看到它,因为所有字段都匹配参数,但是SQL中的Case语句支持可选的Else参数。 这意味着,如果该字符不是When子句中规定的其他字符,您也将看到“ Unknown”输出。

That’s one use of the SQL Case statement (equality version of it). There’s also a searched expression version of it that allow us to work on a range. The following query is based on the price range for a product:

这是SQL Case语句(它的等同版本)的一种用法。 还有一个搜索表达式版本,它使我们可以处理范围。 以下查询基于产品的价格范围:

USE AdventureWorks2012;
GO
SELECT ProductNumber,
       Name,
       "Price Range" = CASE
                           WHEN ListPrice = 0
                           THEN 'Not for resale'
                           WHEN ListPrice < 100
                           THEN 'Under $100'
                           WHEN ListPrice >= 100
                                AND ListPrice < 500
                           THEN 'Under $500'
                           WHEN ListPrice >= 500
                                AND ListPrice < 1000
                           THEN 'Under $1000'
                           ELSE 'Over $1000'
                       END
FROM Production.Product;
GO

Now, instead of doing SQL case statement followed by a column name we just do Case, When, and then column name with the output range and what we want to print out. The above query returns the “Price Range” as a text comment based on the price range for a product:

现在,我们只需要执行Case,When,然后是具有输出范围和我们要打印的内容的列名,而不是执行SQL Case语句后跟一个列名。 上面的查询根据产品的价格范围返回“价格范围”作为文本注释:

Results of a query that displays how to work on a range

Now, let’s see a couple of quick examples when a SQL Case statement can be also used because a lot of times and the most common place you’re going to see a Case statement in SQL is in a Select list to do things like we did above to modify and work with the output. But a lot of times and in some more advanced and complex stuff like stored procedures, you’ll see SQL Case statement in places like Order by and/or SQL Where Case clause.

现在,让我们看几个可以同时使用SQL Case语句的简单示例,因为在很多情况下,您将在SQL中看到Case语句的最常见地方是在Select列表中,以执行与我们相同的操作上面的内容进行修改并使用输出。 但是很多时候,在一些更高级和更复杂的东西(如存储过程)中,您会在诸如Order by和/或SQL Where Case子句之类的地方看到SQL Case语句。

While this can be a little outside of the realm or outside the comfort level of the basic query class, it’s good to get familiar with those as well because you’re bound to come across at some day and it’s good to know why they’re there and see the power of Case statement in SQL.

尽管这可能超出基本查询类的范围,也可能超出基本查询类的舒适度,但也要熟悉这些查询,这是一件好事,因为您一定有一天会碰到这一点,并且知道它们为什么会在那里,了解SQL中Case语句的功能。

Here’s an example with the Order by. Let’s say we want to order the results of our products. Run a quick Select statement to retrieve everything from the table:

这是订购依据的示例。 假设我们要订购产品的结果。 运行快速的Select语句以检索表中的所有内容:

SELECT *
FROM Production.Product p

Note that we are interested in the “MakeFlag” column which is a Flag data type and contains information if the product is purchased (0) or is manufactured in-house (1):

请注意,我们对“ MakeFlag”列感兴趣,该列是Flag数据类型,其中包含有关购买的产品(0)还是内部制造的信息(1):

Results of a query that displays an example without the Order by

Now, let’s say we want to order this results list and show up the products that were purchased first and then the ones manufactured in-house. This is easily done just by adding the SQL Case with “MakeFlag” when it’s 0, then order by “ProductID” descending:

现在,假设我们要订购此结果列表,并显示首先购买的产品,然后显示内部制造的产品。 只需在SQL Case中添加“ MakeFlag”(当其为0时),然后按“ ProductID”降序进行排序,即可轻松实现:

SELECT *
FROM Production.Product p
ORDER BY CASE MakeFlag
             WHEN 0
             THEN ProductID
         END DESC;

Everything up to row 265 is purchased and the rest is manufactured in-house. And that is how SQL Case statement is used in an Order by clause:

直到265行的所有物品都已购买,其余的都在内部制造。 这就是在Order by子句中使用SQL Case语句的方式:

Results of a query that displays an example with the Order by

Here’s another example with the SQL Where Case. This might not be a good SQL Where Case statement because the query below does not make any sense, right?

这是SQL Where Case的另一个示例。 这可能不是一个好SQL Where Case语句,因为下面的查询没有任何意义,对吧?

SELECT * FROM Production.Product p
WHERE
1 = CASE WHEN ListPrice < 100 THEN 1 ELSE 0 END

You’re probably thinking we could just say Select everything from “Product”, where “ListPrice” is less than 100. Yes, but bear with me. The Where clause says 1 equals case when the price is less than a 100, output one, else 0 end. What we’re actually doing here is we’re saying when 1 equals 1, return the row and when 1 equals 0, do not return the row. In this particular case, when the price is less than a 100 it will return the row and when it’s greater than a 100 it will not return anything.

您可能以为我们可以说“从“产品”中选择所有内容,其中“标价”小于100。是的,但是请允许我。 Where子句说1等于当价格小于100时的情况,输出1,否则为0结束。 我们实际上是在说1等于1时,返回行,而1等于0时,不返回行。 在这种特殊情况下,当价格小于100时,它将返回行;而当价格大于100时,它将不返回任何内容。

If we do a quick Select of everything, we get 504 rows returned:

如果快速选择所有内容,则会返回504行:

Results of a query that displays an example without the SQL Where Case

If we include the Where clause with the SQL Where Case in it, then we get 290 rows returned:

如果我们在其中包含SQL Where Case的Where子句,则将返回290行:

Results of a query that displays an example with the SQL Where Case

This still might not look like something useful right off the bat, but you’ll most likely come across a situation where you must make a decision in the SQL Where Case. Well, the SQL Case statement is a great start. Here’s a good analogy. In databases a common issue is what value do you use to represent a missing value AKA Null value. Here we can’t do equalities because we can’t say things like “where a field equals Null” because Null does not equal 0. This is actually a perfect example when to use the Case statement in SQL.

这看起来似乎并非一帆风顺,但您很可能会遇到必须在SQL Where Case中做出决定的情况。 好吧,SQL Case语句是一个很好的开始。 这是一个很好的类比。 在数据库中,一个常见的问题是您使用什么值来表示缺失值(即AKA空值)。 这里我们不能做相等,因为我们不能说“字段等于Null”之类的东西,因为Null不等于0。这实际上是在SQL中使用Case语句的完美示例。

I hope you found this article on the Case statement in SQL helpful and I thank you for reading.

希望本文对SQL中的Case语句有所帮助,并感谢您的阅读。

翻译自: https://www.sqlshack.com/querying-data-using-the-sql-case-statement/

sql语句 case

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值