簡體   English   中英

根據另一列的值條件添加/選擇 SQL 中的多個列

[英]Add/Select mulitiple columns in SQL based on another column's value condition

我正在使用 SQL 服務器。 這是場景:

假設我有一個tableA

UserId  UserName  TransactionType   TransactionDateTime
1       Staff1    NULL              NULL
2       Staff2    1                 2020-08-12 03:11:20.4871383
2       Staff2    2                 2020-08-12 03:41:33.4850314
3       Staff3    2                 2020-08-12 03:41:33.4848626
3       Staff3    1                 2020-08-12 03:11:20.4869688

我想查詢如下結果:

UserId  UserName  ClockInTime                     ClockOutTime
1       Staff1    NULL                            NULL
2       Staff2    2020-08-12 03:11:20.4871383     2020-08-12 03:41:33.4850314
3       Staff3    2020-08-12 03:11:20.4869688     2020-08-12 03:41:33.4848626

所以條件是如果type是1那么transactiondatetime就是clockintime,如果type是2那么它就是clockouttime。

我嘗試使用“case when”:

Select UserId, UserName, 
case when TransactionType = 1 Then TransactionDateTime else null End as ClockInTime,
case when TransactionType = 2 Then TransactionDateTime else null End as ClockOutTime
From tableA

並以這種方式返回 5 行:

UserId  UserName    ClockInTime                  ClockOutTime
1       Staff1      NULL                         NULL
2       Staff2      2020-08-16 03:11:20.4871383  NULL
2       Staff2      NULL                         2020-08-16 03:41:33.4850314
3       Staff3      NULL                         2020-08-16 03:41:33.4848626
3       Staff3      2020-08-16 03:11:20.4869688  NULL

任何幫助是極大的贊賞!!

您可以使用聚合:

select UserId, UserName, 
       max(case when TransactionType = 1 Then TransactionDateTime End) as ClockInTime,
       max(case when TransactionType = 2 Then TransactionDateTime End) as ClockOutTime
from tableA
group by UserId, UserName;

這適用於您的示例數據,因為每個用戶最多有兩行。 如果您的真實數據更復雜,這將只返回每個數據的最大值。

但是,這種情況可能會變得相當復雜。 如果這是你真正需要的,你應該問一個問題。 一定要說明當給定類型的交易有多個/丟失時該怎么做——或者清楚地解釋為什么這是不可能的。

我認為這樣的事情會做到這一點:

    SELECT a.UserId, 
           a.UserName,
           CASE WHEN a.TransactionType = 1 
                THEN a.TransactionDateTime 
                ELSE null END AS ClockInTime,
           b.ClockOutTime
    FROM TableA a
    LEFT JOIN ( 
    
    SELECT UserId, 
           UserName,
           TransactionDateTime AS ClockOutTime
    FROM TableA 
    WHERE TransactionType = 2
   ) b
   ON a.UserId = b.UserId 

我沒有對此進行測試 - 只是直接編寫它,我認為它應該可以工作,當然你想要一個帶有連接的子查詢。

該表可以保持連接到自身。 如果用戶一遍又一遍地打卡和打卡,這種方法可能很有用(有額外的日期不等式)。

Select UserId, UserName, ct1.TransactionDateTime ClockInTime, ct2.TransactionDateTime ClockOutTime
From tableA ta  left join tableA tb on ta.UserId=tb.UserId
where ta.TransactionType = 1 and tb.TransactionType = 2;

暫無
暫無

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

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