关于嵌套SELECT语句的子查询

enyiok 2015-03-29 02:21:31
以下为表结构例子
A B C 日期
A1 B1 1 20150301
A1 B2 0 20150302
A2 B2 1 20150303
A2 B4 1 20150304
A1 B4 1 20150305

我想通过该语句 把查询出来的结果做为条件,放到语句2上查询
我的子查询是这样写的 语句1: select A,count(A) as 精确度 from table where C=1 and 日期>=20150301 and 日期<=20150305 group by A having count(A)=2
该语句查询出上面的结果应为 A 精确度
A1 2
A2 2

此时查询出来的结果有两条记录 A1 A2 ,我需要将A1 A2 作为条件执行以下语句2:
select 日期,B,COUNT(B) AS 出现最多次 from table where 日期=20150305 and (A='A1' or A='A2') group by B,日期 having count(B)>0 order by 日期,出现最多次 desc

请问如何写才可行,让上面的的语句1的出来的结果作为条件嵌入到下面语句2中执行,如何实现,请高手赐教,谢谢!
...全文
830 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
hepe00 2015-03-29
  • 打赏
  • 举报
回复
以下只提供技术的可实现方式,但逻辑需要自己考虑是否可调整:
SELECT * FROM 
(
select A,count(A) as 精确度 from table 
where C=1 and 日期>=20150301 and 日期<=20150305 group by A having count(A)=2
) AS t
CROSS APPLY
(
select 日期,B,COUNT(B) AS 出现最多次 from table where 日期=20150305 and (A='A1' or A='A2')  group by B,日期 having count(B)>0 order by 日期,出现最多次 desc
) AS p
enyiok 2015-03-29
  • 打赏
  • 举报
回复
怎么沉下去了,赐教一下高手
frankl123 2015-03-29
  • 打赏
  • 举报
回复
with tb1 as ( select A,count(A) as 精确度 from table where C=1 and 日期>=20150301 and 日期<=20150305 group by A having count(A)=2 ), tb2 as ( select 日期,B,COUNT(B) AS 出现最多次 from table where 日期=20150305 and A in ( select A from tb1 ) group by B,日期 having count(B)>0 order by 日期,出现最多次 desc ) select * from tb2

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧