我有一个示例数据如下:
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 in这个例子)在一个查询中。
我尝试使用row_number()但是没有达到目的。有没有办法得到这个。
答案 0 :(得分:4)
这是你想要的吗?
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;
子查询计算第一个在线记录的日期。查询的其余部分只会执行您想要的计数。
答案 1 :(得分:0)
Relative Self
答案 2 :(得分:0)
确定第一个在线日期,然后进行2次计数。
;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
答案 3 :(得分:0)
其他选项与 correlation 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
答案 4 :(得分:0)
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)