27,579
社区成员
发帖
与我相关
我的任务
分享
if not object_id(N'Tempdb..#Tmp_Tbl') is null
drop table #Tmp_Tbl
Go
Create table #Tmp_Tbl(
org varchar(10),
code varchar(10),
jg1 int,
s1 int,
rq date)
GO
Insert #Tmp_Tbl
Select 'C1', '0001' , 20 , 5 , '2016-04-20' union all
Select 'C2' , '0001', 19 , 0 , '2015-01-01' union all
Select 'C3' , '0001' , 21 , 1 , '2017-02-02' union all
Select 'C1' , '0002' , 10 , 3 , '2016-10-10' union all
Select 'C2' , '0002', 8 , 0 , '2016-12-12' union all
Select 'C3' , '0002' , 9 , 2 , '2015-12-12' union all
Select 'C1' , '0003', 6 , 0 , '2015-03-03' union all
Select 'C2' , '0003' , 6, 0 , '2017-12-12' union all
Select 'C3' , '0003', 7 , 0 , '2016-11-11' union all
Select 'C1' , '0004' , 8 , 0, null union all
Select 'C2' , '0004', 9 , 2, null union all
Select 'C3' , '0004' , 6 , 3, null
--表A查询出, 当sl(C1,C2,C3同时)=0时,不显示;
--当sl(C1,C2,C3有一项)<>0时,即使对应的sl=0,取rq最新的,
--当 rq is null 时,选ls<>0并且jg1最大的那项,如果ls和jg1也重复,只选一个,不能重复
if not object_id(N'Tempdb..#Tmp_A') is null
drop table #Tmp_A
Go
--s1不同时为零且rq is not null
Select *
into #Tmp_A
From #Tmp_Tbl
Where code not in (Select code
From (Select code,SUM(s1) as s1 From #Tmp_Tbl group By Code) a
Where s1=0 )
and rq is not null
if not object_id(N'Tempdb..#Tmp_B') is null
drop table #Tmp_B
Go
--s1不同时为零且rq is null
Select *
into #Tmp_B
From #Tmp_Tbl
Where code not in (Select code
From (Select code,SUM(s1) as s1 From #Tmp_Tbl group By Code) a
Where s1=0 )
and rq is null
Select *
From #Tmp_A a
Where a.rq=(Select MAX(rq) From #Tmp_A b where b.code=a.code)
union
Select *
From #Tmp_B a
Where a.jg1=(Select MAX(jg1) From #Tmp_B b where b.code=a.code)
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([org] nvarchar(22),[code] nvarchar(24),[jg1] int,[sl] int,[rq] nvarchar(30))
Insert #T
select N'C1',N'0001',20,5,N'2016-04-20' union all
select N'C2',N'0001',19,0,N'2015-01-01' union all
select N'C3',N'0001',21,1,N'2017-02-02' union all
select N'C1',N'0002',10,3,N'2016-10-10' union all
select N'C2',N'0002',8,0,N'2016-12-12' union all
select N'C3',N'0002',9,2,N'2015-12-12' union all
select N'C1',N'0003',6,0,N'2015-23-23' union all
select N'C2',N'0003',6,0,N'2017-12-12' union all
select N'C3',N'0003',7,0,N'2016-11-11' union all
select N'C1',N'0004',8,0,null union all
select N'C2',N'0004',9,2,null union all
select N'C3',N'0004',6,3,null
Go
--测试数据结束
SELECT b.*
FROM #T b
JOIN ( SELECT a.code ,
MAX(rq) AS rq ,
MAX(jg1) AS jg1
FROM #T a
WHERE a.code IN ( SELECT code
FROM #T
WHERE sl <> 0
GROUP BY code )
GROUP BY code
) t ON t.code = b.code
AND ( ( t.rq IS NOT NULL
AND b.rq = t.rq
)
OR ( t.rq IS NULL
AND t.jg1 = b.jg1
)
)