sql多表查询问题,重复记录里取时间最大的,并且关联test3表获取名字并统计数量,谢谢,在线等
现在有test1,test2,test3 3个表,test1,test2表的结构分别是
Id,memberId,jb1 jb2 jb3 jb4 CreateTime 7个字段
比如test1里有数据
1 22 1 2 3 4 2013-4-9
2 22 3 1 5 6 2013-4-6
3 24 5 6 7 8 2013-4-2
4 22 4 2 7 4 2013-4-11
5 6 8 2 3 6 2013-4-19
比如test2里有数据
1 22 1 2 3 7 2013-4-29
2 23 3 1 5 6 2013-4-16
3 24 2 6 7 8 2013-4-12
4 22 1 2 3 5 2013-4-18
5 6 5 2 3 4 2013-4-6
test3表的结构是:
Id Title 比如test3里有数据
1 疾病1
2 疾病2
3 疾病3
4 疾病4
5 疾病5
6 疾病6
7 疾病7
8 疾病8
我现在想取的数据是:
1,test1跟test2表里不重复memberId的数据,并且取CreateTime最大的
2,统计出疾病的数量来
按照上面的案例列表,我想要的数据应该是
第1,不重复的MemberId并且Createtime最大的
22 疾病1 疾病2 疾病3 疾病7 2013-4-29
test2表的第1条数据
24 疾病5 疾病6 疾病7 疾病8 2013-4-12 test2表的第3条数据
6 疾病8 疾病2 疾病3 疾病6 2013-4-19 test1表的第5条数据
23 疾病3 疾病1 疾病5 疾病6 2013-4-16 test2表的第2条数据
第2,统计出疾病的数量来
疾病1 2
疾病2 2
疾病3 3
疾病5 2
疾病6 3
疾病7 2
疾病8 2
有不就明白的地方问我,我在线等, 谢谢各位 sql mssql
[解决办法]
没有测试
第1个问题
select * into #tmp from test1
union all
select * from test2
select memberId,
c1.Title,c2.Title,c3.Title,c4.Title
createtime
from #tmp t
inner join test c1 on c1.id=jb1
inner join test c2 on c2.id=jb2
inner join test c3 on c3.id=jb3
inner join test c4 on c4.id=jb4
where not exists(select 1 from #tmp where memberId=t.memberId and createtime
>t.createtime
)
第2个问题
select * into #tmp1
from #tmp t
where not exists(select 1 from #tmp where memberId=t.memberId and createtime
>t.createtime
)
select a.id,b.Title ,count(*) as num
from(
select jb1 as id from #tmp1
union all
select jb2 from #tmp1
union all
select jb3 from #tmp1
union all
select jb4 from #tmp1
)a,test3 b
where a.id=b.id
group by a.id,b.Title
SELECT * INTO #F1 FROM (SELECT * FROM test1 UNION ALL SELECT * FROM test2)T
SELECT * INTO #F2 FROM (SELECT * FROM #F1 T WHERE NOT EXISTS(SELECT 1 FROM #F1 WHERE memberId=T.memberId AND CreateTime>T.CreateTime))T
SELECT
C.Title,T.NUM AS 数量
FROM
(
SELECT JB,COUNT(1) AS NUM
FROM
(
SELECT JB1 AS JB FROM #F2
UNION ALL
SELECT JB2 FROM #F2
UNION ALL
SELECT JB3 FROM #F2
UNION ALL
SELECT JB4 FROM #F2
)T
GROUP BY
JB
)T INNER JOIN TEST3 C ON T.JB=c.id
DROP TABLE #F1,#F2
select * from
(
select memberId,jb,COUNT(*) as total from
(
select memberId,jb1 as jb
from test1,test2
union
select memberId,jb2 as jb
from test1,test2
union
select memberId,jb3 as jb
from test1,test2
union
select memberId,jb4 as jb
from test1,test2
) t group by memberId,jb
) a where total !=0