简体   繁体   中英

Return multiple count values

this is probably a simple question and I've searched but not sure of what the official description is of what I want to do....

I've a table recording details of buildings with columns recording, yes no or not recorded against things such as broadband, telephone etc...

I'm trying to build a query which returns each value, a bit like a report, but want to keep things where I'm not running an individual query for each value (Remembering DRY!).

If I know I'm looking for either "yes", "no" or "not recorded", is it possible to do one query to return all 3 values separately?

i only currently know how to return individual values and I don't want to create a page full of repeated code!

Table: sites (excuse the poor layout!)

:ID--SITE----------------BBAND----PHONE
:1---Station House-----Yes---------Yes
:2---Drakes Building---Yes---------No
:3---Summer Lodge----No----------Yes
:4---Prospect House---Yes--------Yes

current code is (i don't know how to do multiple counts):

$result=mysql_query("SELECT count(*) as bband from sites WHERE bband =     'Yes'");
$data=mysql_fetch_assoc($result);
echo "Broadband Yes:"; 
echo $data['bband'];

I'd then have to repeate this code for 'No' and then again for 'Not Recorded'. That method is wrong as its very inefficient.

Ideally I'd like to be able to echo/print the individual results so I can add them to a table/layout .

SELECT SUM(val = 'no')as count_no, SUM(val='yes') as count_yes, SUM(val='not') as count_not FROM...

val = 'no' equals 1 if val is equal to 'no' or 0 if it's not. Thus with SUM(val = 'no') you count the cases where val = 'no'. And therefore you can "count" different val = pieces without placing it in the WHERE-part of your sql-statment.

I think you are looking for something like that:

SELECT *, COUNT(CASE WHEN value="yes" THEN 1 END) AS 'total_yes',
          COUNT(CASE WHEN value="no" THEN 1 END) AS 'total_no',
          COUNT(CASE WHEN value="not recorded" THEN 1 END) AS 'total_not_recorded'
FROM myTable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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