ds1379551 2014-09-29 12:49
浏览 73
已采纳

Count或SUM()的多列简单查询

I need to total up values stored in upto 17 columns in the same table using php, and trying to keep the query as small and simple as possible:

table is Setup like so:

  | siterun1 | siterun2 | siterun3 | siterun4 | siterun5 | siterun6 | siterun17 |
  |  0       | 5        | 4        | 1        | 0        | 0        | 3         |

is there a quick way of writing a query that counts up all the values from column siterun1 all the way upto siterun17 ?

at the moment i started to write out;

SELECT SUM(siterun1) as 'siterun1', SUM(siterun2) as 'siterun2', 
       SUM(siterun3) as 'siterun3',
      (SUM(siterun1) + SUM(siterun2) + SUM(siterun3)) as 'Total' 
 FROM dataTable WHERE sessionID=1

but this is going to get very big upto 17 columns with the possibility of more at a later date.

basically i need it to add up the columns and echo the result.

any help on this would be great, my above code will work but i'm not sure if its the best approach.

  • 写回答

2条回答 默认 最新

  • dongzhuohan7085 2014-09-29 13:08
    关注

    For the total you can use a single SUM, so instead of

    (SUM(siterun1) + SUM(siterun2) ...) Total
    

    you can write

    SUM(siterun1 + siterun2 ...) Total
    

    or as mentioned in the comments you can use php (array_sum) to do the summing.

    $query = "SELECT SUM(siterun1) as 'siterun1', 
    SUM(siterun2) as 'siterun2', 
    SUM(siterun3) as 'siterun3'
    FROM dataTable WHERE sessionID=1";
    
    $rs = mysqli_query($query);
    $r = mysqli_fetch_assoc($rs);
    
    $r['Total'] = array_sum($r); //assumes you only have sum columns in your select
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答