簡體   English   中英

如何在sql中檢查第一列的行是否大於第二列(使用IF語句)

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

我寫了一個查詢來創建一個只有一列的表

CREATE TABLE ORDER( 
   Order_Date DATE NOT NULL
)

我在欄中插入了兩個值

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

如何使用IF語句檢查第一行是否大於或小於第二行?

SQL表表示無序集。 表中沒有“第一”行或“第二”行。

如果包含標識列,則可以執行所需的操作:

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

現在,您可以查看OrderIdOrderDate是否處於相同順序。 就像是:

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;

注意,我還將該表重命名為Orders Order對於表來說確實是個壞名字,因為它既是SQL關鍵字又是保留字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM