两个条件都满足时双录SQL

Double record when both conditions are met SQL

我的 table 中有一条记录:

我需要创建一个订单状态列:如果订单已创建则为“1”,如果订单已取消则为“0”。

所以对于这个例子,当同时存在创建和取消时,我需要两个状态。最后的table应该是:

我该怎么做?

一种方法是多次加入您的 table 并限制您的加入以限制您的结果集;这是一种简单的数据透视方法,但它会影响性能。

DECLARE @a TABLE (id INT, createdate date,canceldate date,reportdate DATE)

INSERT INTO @a (id, createdate, canceldate, reportdate)
VALUES (
    1, -- id - int
    GETDATE(), -- createdate - date
    GETDATE(), -- canceldate - date
    GETDATE() -- reportdate - date
)

INSERT INTO @a (id, createdate, canceldate, reportdate)
VALUES (
    2, -- id - int
    GETDATE(), -- createdate - date
    null, -- canceldate - date
    GETDATE() -- reportdate - date
)

SELECT a.id,a.createdate,a.canceldate,a.reportdate,CASE WHEN a1.id IS NOT NULL THEN '1' ELSE 0 END AS 'createdInd'
,CASE WHEN a2.id IS NOT NULL THEN '1' ELSE 0 END AS 'CancelledInd'

FROM @a a 
LEFT  JOIN @a a1 ON a.id = a1.id AND a1.createdate IS NOT NULL
LEFT JOIN @a a2 ON a.id = a2.id AND a2.canceldate IS NOT NULL 


id  createdate  canceldate  reportdate  createdInd  CancelledInd
1   2021-04-07  2021-04-07  2021-04-07  1   1
2   2021-04-07  NULL    2021-04-07  1   0

我想你可以像这样简单地做一个联合:

select OrderCreateDate, OrderCancelDate, ReportDate, 1 as OrderState
  from your_table
  where orderCreateDate is not null
union all
select OrderCreateDate, OrderCancelDate, ReportDate, 0 as OrderState
  from your_table
  where orderCancelDate is not null

加入 table 查询 returns 值 10:

SELECT t.*, s.OrderState
FROM tablename AS t
INNER JOIN (SELECT 1 AS OrderState UNION ALL SELECT 0) AS s
ON (s.OrderState = 1 AND t.OrderCreateDate IS NOT NULL)
OR (s.OrderState = 0 AND t.OrderCancelDate IS NOT NULL)