dsa122870 2015-04-10 07:59
浏览 142

返回多个计数值

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 .

  • 写回答

2条回答 默认 最新

  • drny60365 2015-04-10 08:10
    关注
    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 有没有可以帮我搞一个微信建群链接,包括群名称和群资料群头像那种,不会让你白忙
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题