[英]Counting rows based on a criteria in sql server
我有一個示例數據,如下所示:
field1 onlineoffline trxndate
--------------------------------
F1 Offline 2018-04-03
F1 Online 2018-04-04
F1 Online 2018-04-05
F1 Offline 2018-04-06
F1 Offline 2018-04-07
F1 Offline 2018-04-08
F1 Offline 2018-04-09
F1 Online 2018-04-10
F1 Offline 2018-04-11
我需要基於trxndate(在此示例中為2)獲得第一次在線記錄后在線記錄的計數,也想基於trxndate(在此示例中為7)獲得第一次在線記錄后所有記錄的計數。在一個查詢中。
我嘗試使用row_number(),但並沒有達到目的。 有沒有辦法做到這一點。
這是你想要的嗎?
select count(*) as num_records,
sum(case when onlineoffline = 'online' then 1 else 0 end) as num_online_record
from (select t.*,
min(case when onlineoffline = 'online' then trxndate end) over () as min_online_td
from t
) t
where trxndate > min_online_td;
子查詢計算第一個在線記錄的日期。 查詢的其余部分僅執行所需的計數。
select -- count only Online rows
online_count = sum(case when onlineoffline = 'Online' then 1 else 0 end),
-- count all rows
all_count = count(*)
from tbl
where trxdate >
-- find the first trxdate that is online
(select top 1 trxdate from tbl where onlineoffline = 'Online' order by trxdate)
確定第一個在線日期,然后進行兩次計數。
;WITH MinimumOnlineDate AS
(
SELECT
MinDate = MIN(T.trxndate)
FROM
YourTable AS T
WHERE
T.onlineoffline = 'Online'
)
SELECT
TotalAfterFirstOnline = COUNT(1),
TotalOnlineAfterFirstOnline = COUNT(CASE WHEN T.onlineoffline = 'Online' THEN 1 END)
FROM
YourTable AS T
INNER JOIN MinimumOnlineDate AS M ON T.trxndate > M.MinDate
另一種選擇是與相關 subquery
select count(*) as online_counts, max(t1.counts) as no_of_onlines
from table t
join (
select distinct min(trxndate) over() trxndate, count(*) over (order by field1) Counts
from table t
where onlineoffline = 'Online' and trxndate <> (
select min(trxndate) from table where onlineoffline = 'Online' and field1 = t.field1)
)t1 on t.trxndate >= t1.trxndate
select
sum(case when onlineoffline = 'Online' then 1 else 0 end) online,
count(*) all
from table
where trxdate > (select top 1 trxdate from table where onlineoffline = 'Online' order by trxdate)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.