日期:2014-05-16  浏览次数:20882 次

++++++++++++++期待高手帮我解决一个mysql 查询语句++++++++++
有一张表tableA,有两个属性,分别为username,status,如下:
  username               status
    A1                             1
    A2                             3
    A1                             3
    A3                             1
    A2                             3
    A4                             2

我想求出:以username作为分组,status的值为3所占的百分比,
理想结果如下:
    A1                           50%
    A2                           100%
    A3                             0%
    A4                             0%

------解决方案--------------------
mysql> select * from table1;
+----------+--------+
| username | status |
+----------+--------+
| a1 | 1 |
| a2 | 3 |
| a2 | 5 |
+----------+--------+
3 rows in set (0.01 sec)

mysql>


select username, sums/sumall
from (select username ,sum(status) as sums from table1 group by username ) tb ,
(select sum(status) as sumall from table1 ) tbs ;
+----------+-------------+
| username | sums/sumall |
+----------+-------------+
| a1 | 0.1111 |
| a2 | 0.8889 |
+----------+-------------+
2 rows in set (0.00 sec)



------解决方案--------------------
select ttotal.username ,concat(ttotal.sums*100 / thas3.sums, "% ") as result from (select username ,count(*) as sums from table1 group by username ) as ttotal left join (select username ,count(*) as sums from table1 where status= '3 ' group by username ) thas3 on ttotal.username = thas3.username

楼主验证一下。我这里没有数据,就不验证了。

------解决方案--------------------
create table #t(username varchar(10),status int)

insert into #t
select 'A1 ',1 union all
select 'A2 ',3 union all
select 'A1 ',3 union all
select 'A3 ',1 union all
select 'A2 ',3 union all
select 'A4 ',2

select
username,
cast(cast((select count(*) from #t where username=A.username and status=3 ) *1.0
/(select count(*) from #t where username=A.username) as decimal(10,1)) * 100 as varchar(10)) + '% ' as 占比
from #t as A
group by username

drop table #t
------解决方案--------------------
select tableA.username,t.s/count(tableA.username) status
from tableA,(select username,count(status) s from tableA where status = 3 group by username) t
where tableA.username = t.username group by num;