SQL语句请教
最近做一个项目,其中有个银行对帐的功能
首先 表如下:
id type account
1 1 1000
2 1 2000
3 1 2000
4 1 3000
5 1 4000
6 2 1000
7 2 1000
8 2 2000
9 2 5000
type 1:银行单, 2:公司单
现在要做个统计: 统计银行单与公司单金额相同的单数,比如 id 1和 id6两张,
可是这里有个难点,如果一个金额两种单分别有多单的金额相同,则只能取少的一方,比如1000的金额,假如银行单有10张,公司单有2张,真实相同的单应该为2张而不是10张,
我上面的示例应该统计出的结果为2,请问,这种查询我该如何下手,才能统计出正确结果。
谢谢~
------解决方案--------------------
--帐户相同单数
select A.account,min(case when A.cnt> B.cnt then B.cnt else A.cnt end) as 帐户相同单数
from
(select account,count(*) AS cnt from 表名 where type=1 group by account) A
inner join
(select account,count(*) AS cnt from 表名 where type=2 group by account) B on A.account=B.account
group by A.account
--总计相同单数
select sum(cnt) as 总计相同单数
from
(
select A.account,min(case when A.cnt> B.cnt then B.cnt else A.cnt end) as cnt
from
(select account,count(*) AS cnt from 表名 where type=1 group by account) A
inner join
(select account,count(*) AS cnt from 表名 where type=2 group by account) B on A.account=B.account
group by A.account
) T
[解决办法]
楼主帮个忙,差30分就升级了