試試這個。如果我做了一些不正確的假設,我已經包含了樣本表和我使用的數據。
create table person
(
prsnRefId int,
prsnCode varchar(50),
prsnName1 varchar(50),
prsnName2 varchar(50)
);
create table IOTransaction
(
ioPrsnRefId int,
ioTransactionDate datetime,
ioStatus int
);
insert into person values(1,'code1','Bob','Carolgees');
insert into person values(2,'code2','Diana','Dors');
insert into IOTransaction values(1,'01-jan-2016 09:00:00',0);
insert into IOTransaction values(1,'01-jan-2016 12:00:00',1);
insert into IOTransaction values(1,'01-jan-2016 13:00:00',0);
insert into IOTransaction values(1,'01-jan-2016 18:00:00',1);
insert into IOTransaction values(1,'02-jan-2016 09:01:00',0);
insert into IOTransaction values(1,'02-jan-2016 12:01:00',1);
insert into IOTransaction values(1,'02-jan-2016 13:01:00',0);
insert into IOTransaction values(1,'02-jan-2016 18:01:00',1);
insert into IOTransaction values(2,'01-jan-2016 08:30:00',0);
insert into IOTransaction values(2,'01-jan-2016 12:30:00',1);
insert into IOTransaction values(2,'01-jan-2016 13:30:00',0);
insert into IOTransaction values(2,'01-jan-2016 17:45:00',1);
insert into IOTransaction values(2,'02-jan-2016 08:31:00',0);
insert into IOTransaction values(2,'02-jan-2016 12:31:00',1);
insert into IOTransaction values(2,'02-jan-2016 13:31:00',0);
insert into IOTransaction values(2,'02-jan-2016 17:46:00',1);
with ins as (
select ioPrsnRefId,
convert(date, ioTransactionDate) as date,
IOTransactionDate,
row_number() over (partition by ioPrsnRefId, convert(date, ioTransactionDate) order by ioTransactionDate) rn
from IOTransaction
where ioStatus = 0
),
outs as (
select ioPrsnRefId,
convert(date, ioTransactionDate) as date,
IOTransactionDate,
row_number() over (partition by ioPrsnRefId, convert(date, ioTransactionDate) order by ioTransactionDate desc) rn
from IOTransaction
where ioStatus = 1
)
SELECT p.prsnCode [Sicil No]
,p.[prsnName1]
,p.[prsnName2]
,t.[ioTransactionDate]
,[Giris/Cikis] = (
case
when [ioStatus] = 0 then 'Giris'
when [ioStatus] = 1 then 'Cikis'
else 'Uzaya Gitti' end)
FROM [IOTransaction] t
left join dbo.Person p on t.ioPrsnRefId = p.prsnRefId
left join ins on p.prsnRefId = ins.ioPrsnRefId
and t.ioTransactionDate = ins.ioTransactionDate
left join outs on p.prsnRefId = outs.ioPrsnRefId
and t.ioTransactionDate = outs.ioTransactionDate
where ins.rn = 1 or outs.rn=1
我不能編輯問題,查詢似乎工作正常,但它的作品約3分鐘列出。 新的問題是,有什麼辦法來扣緊這個查詢? –
爲什麼不在'select'語句中放置'Min(t。[ioTransactionDate]'和'Max(t。[ioTransactionDate])',然後刪除where子句或放入'TransactionDate'的日期範圍 –