简体   繁体   English

如何在sql中检查第一列的行是否大于第二列(使用IF语句)

[英]How to check if the row of the first column is greater than the second in sql (Using IF Statement)

I wrote a query to create a table with one column 我写了一个查询来创建一个只有一列的表

CREATE TABLE ORDER( 
   Order_Date DATE NOT NULL
)

I inserted two values into the column 我在栏中插入了两个值

--Order_Date--
2018-05-21
2018-01-21

How to check if the first row is greater or less than the second row using IF statement? 如何使用IF语句检查第一行是否大于或小于第二行?

SQL tables represent unordered sets. SQL表表示无序集。 There is no "first" row or "second" row in a table. 表中没有“第一”行或“第二”行。

You can do what you want if you include an identity column: 如果包含标识列,则可以执行所需的操作:

CREATE TABLE ORDERS ( 
   OrderId IDENTITY(1, 1) PRIMARY KEY,
   Order_Date DATE NOT NULL
);

Now, you can see if OrderId and OrderDate are in the same order. 现在,您可以查看OrderIdOrderDate是否处于相同顺序。 Something like: 就像是:

select (case when max(case when seqnum = 1 then order_date end) >
                  max(case when seqnum = 2 then order_date end)
             then 'greater than'
             when max(case when seqnum = 1 then order_date end) =
                  max(case when seqnum = 2 then order_date end)
             then 'equal'
             when max(case when seqnum = 1 then order_date end) <
                  max(case when seqnum = 2 then order_date end)
             then 'less than'
        end) as comparison
from (select o.*, row_number() over (order by OrderId) as seqnum
      from orders o
     ) o;

Notice that I also renamed the table to Orders . 注意,我还将该表重命名为Orders Order is a really bad name for a table because it is a SQL keyword and a reserved word as well. Order对于表来说确实是个坏名字,因为它既是SQL关键字又是保留字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM