求问一个两表查询的SQL语句。

环境是:
一个数据库里有两个表,分别为A和B。
A表中有A1,A2,A3,A4几个字段,
B表中有B1,B2,B3字段。
A1和B1可以做为索引字段连接两表。
A2字段值一般为:1,0,-1
要求是:以A1字段为索引,查询A2字段中值为1的值占总数的比例,然后按比例值比高到低进行排序,

如:
A表:
A1 A2 A3
人 0 *
和 0 *
人 1 *
人 -1 *
人 1 *

B表:
B1 B2
人 *
和 *
人 *

select A1,A2,cast(A2Count*1.0/AllCount as numeric(5,2)) 所占比例 from
(
select A1,A2,count(0) A2Count, (select count(0) from A表 a inner join B表 b on a.A1=b.B1) AllCount from A表 a inner join B表 b on a.A1=b.B1 group by A1,A2
) aaaa
order by A1,A2,A2Count desc追问

你好。SQL语句是这样的。
提示语法错误,在cast(dpsCount*1.0/AllCount as numeric(5,2)) 中。是你原句的:cast(A2Count*1.0/AllCount as numeric(5,2))

能加上你Q吗?你Q多少?

追答

私信我留下 你QQ

追问

你好,能说下你这语句的思路吗?用了三个Select,,都有什么作用?

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-04-13
declare @zs numeric(18,2)

--总数
select @zs = count(1) from A

--A2=1的数量
select count(1) / @zs from A
where A2 = 1

--1、按照你的描述,和B应该没啥关系,是不是你描述的不清晰?
--2、按照你的描述,A2等于1的,只有一个数,为什么还需要排序?是不是也是因为没有描述清楚?追问

-1,最终的结果要查询B2,B3,B4的数据,A表中的数据主要是排序作用。

-2例子只是说明大致格式,真实数据有大量数据。

真实数据表可能是


另外,能写出完整的SQL吗?

追答

declare @zs numeric(18,2)

--总数
select @zs = count(1) from A
--此处条件可以自己添加

if(object_id('tempdb..#a'))
drop table #a

select count(1) / @zs,A1 into #a from A
WHERE A2 = 1
group by A1
--此处如果没有=1的就不会显示出来,如需要,按如下格式写

/*
select sum(case A2 when 1 then 1 else 0 end),A1 into #a from A
group by A1
*/

select * from #a,B
where #a.A1 = B.B1

--试试看行不行吧

相似回答