不幸的是,我在查詢或理解解決方案方面再次遇到了重大問題。我已經測驗了子查詢和 IF EXISTS 陳述句,但不幸的是它沒有用
我正在尋找車輛已停止但尚未到達的事件數量 - 即當驅動器被取消時
我有一個看起來像這樣的測驗表:
| 光碟 | 事件編號 | 車輛 | 地位 |
|---|---|---|---|
| 2021-10-01 16:15 | ev00001 | 車輛1 | 在途中 |
| 2021-10-01 16:35 | ev00001 | 車輛1 | 到達的 |
| 2021-10-01 16:45 | ev00002 | 車輛3 | 在途中 |
| 2021-10-01 16:50 | ev00002 | 車輛3 | 到達的 |
| 2021-10-01 17:04 | ev00003 | 車輛4 | 在途中 |
| 2021-10-01 17:06 | ev00003 | 車輛5 | 在途中 |
| 2021-10-01 17:10 | ev00003 | 車輛5 | 到達的 |
| 2021-10-01 17:11 | ev00003 | 車輛1 | 在途中 |
| 2021-10-01 17:13 | ev00003 | 車輛3 | 在途中 |
| 2021-10-01 17:18 | ev00003 | 車輛3 | 到達的 |
操作:不同/幾輛車可以駕駛到一個事件,它們具有相同的事件編號我使用 SQL Server,TSQL
輸出應如下所示
| 計數單位取消 |
|---|
| 2 |
.
我已經嘗試過一個子查詢,但我不知道如何在這方面獲得正確的邏輯。或者 if exists 陳述句是最好的方法嗎?
我羞于發布我的嘗試 xD
非常感謝你的幫助
uj5u.com熱心網友回復:
您可以使用LEAD來標識onway后面沒有緊跟的行arrived。然后簡單地計算這些行:
SELECT
[Count Unit Cancel] = COUNT(IsNotArrived)
FROM (
SELECT *,
IsNotArrived = CASE WHEN LEAD(status) OVER (PARTITION BY vehicle, eventnumber
ORDER BY cdts) = 'arrived' THEN NULL ELSE 1 END
FROM YourTable t
) t
WHERE status = 'onway';
資料庫<>小提琴
uj5u.com熱心網友回復:
這可能過于簡單化,但您似乎只是希望每個“在路上”都有一個相應的“到達”,以及差異的數量
select
Sum(case when status='onway' then 1 end)
- Sum(case when status='arrived' then 1 end) CountUnitCancel
from t
uj5u.com熱心網友回復:
使用 antisemijoin 技術的簡單方法:
-- get all vehicles onway (=not yet arrived)
select count(t1.vehicle) as [Vehicle count onway]
from [table] as t1
left join table2 as t2
on t1.vehicle = t2.vehicle
and t1.cdts > t2.cdts
and t2.[status] = 'arrived'
where t1.[status] = 'onway'
and t2.vehicle is null
與exists陳述句相同:
-- get all vehicles onway (=not yet arrived)
select count(t1.vehicle) as [Vehicle count onway]
from [table] as t1
where not exists (
select 2
from table2 as t2
on t1.vehicle = t2.vehicle
and t1.cdts > t2.cdts
and t2.[status] = 'arrived')
where t1.[status] = 'onway'
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/361941.html
標籤:sql-server 查询语句
上一篇:當列不匹配時,SQLServer在INSERT/SELECT上鎖定......但僅在SQLServerManagementStudio中
