繁体   English   中英

在SQL中将查询结果分组

[英]Grouping query results in sql

例如,我有一列:bank_id和status。

使用查询:

SELECT Bank_ID, status FROM int_client_bank WHERE status = 30 or status = 50 or status = 35 or status = 37;

我得到的结果是:

例如。

**id_bank status**
    1, 30
    1, 30
    1, 50
    1, 35
    2, 50
    2, 37

等..

我需要进行查询,以便每个银行都可以算出我是否有一定比例的身份,然后使用php / symfony将其扔到表中。

举例:1个银行:-

status30 - 2 each (20%)
 status50 - 4 each (40%)
 status - 6 each (60%)

2银行等

怎么做?

在SQL中使用分组可按组和状态对分组,并计数每个组中的行:

SELECT Bank_ID, status, COUNT(Bank_ID) count FROM int_client_bank WHERE status = 30 or status = 50 or status = 35 or status = 37 GROUP BY Bank_ID, status;

然后,您可以对所有计数求和,并为每一行计算百分比,例如$row['count'] / $all_count * 100

我相信这就是您要寻找的。 您可以使用子查询在MySQL中完成所有操作。

select 
  myTable.id_bank, myTable.status, count(*) as ct, count(*) / t2.cnt * 100 as pct from myTable
join (
    select id_bank, count(*) AS cnt 
    from myTable
    group by id_bank
  ) as t2 on myTable.id_bank = t2.id_bank
group by myTable.id_bank, myTable.status;

http://sqlfiddle.com/#!2/46834/11

sphirate.thremer:

我有要求:

SELECT Bank_ID, Status, COUNT(Bank_ID) 
FROM int_client_bank 
WHERE status = 30 
  or status = 50 
  or status = 35 
  or status = 37 
GROUP BY Bank_ID, Status;

并查看数据:

"Bank_ID"   "Status"    "COUNT(Bank_ID)"
"1" "30"    "772"
"1" "35"    "58"
"1" "50"    "151"
"2" "30"    "124"
"2" "35"    "27"
"2" "50"    "25"
"3" "30"    "227"
"3" "35"    "16"
"3" "37"    "1"
"3" "50"    "143"
"4" "30"    "337"
"4" "35"    "23"
"4" "37"    "1"
"4" "50"    "98"
"5" "30"    "72"
"5" "35"    "7"
"5" "50"    "9"
"6" "30"    "113"
"6" "35"    "3"
"6" "50"    "68"
"7" "30"    "16"
"7" "50"    "10"
"8" "30"    "13"
"8" "35"    "1"
"8" "50"    "6"
"9" "30"    "16"
"9" "35"    "2"
"9" "50"    "6"
"10"    "30"    "4"
"10"    "35"    "2"
"11"    "30"    "2"
"11"    "50"    "2"
"12"    "30"    "4"
"12"    "35"    "1"
"12"    "50"    "1"
"13"    "30"    "3"
"13"    "50"    "2"
"14"    "30"    "5"
"15"    "30"    "1"
"15"    "50"    "1"
"16"    "30"    "1"
"17"    "30"    "1"
"18"    "30"    "2"

我如何才能将它放在symfony中以制作JsonResponse ?:

return new JsonResponse(array('data' => $result, 'success' => true));:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM