sql多列加上每列的总和

时间:2012-06-20 00:32:32

标签: mysql

使用MySQL,我计算了几年内几个事件(字段)的出现次数。然后我逐年显示这一列。按年分组时,我的查询工作正常。我现在想要添加一个显示年份总和的最终列。如何添加总列数查询?

Event 2008  2009  2010  2011 total  
  A     0     2    0     1     3  
  B     1     2    3     0     6  
etc.

这是真正的查询:

select   
    count(*) as total_docs,  
    YEAR(field_document_date_value) as doc_year,  
    field_document_facility_id_value as facility,  
    IF(count(IF(field_document_type_value ='LIC809',1, NULL)) >0,count(IF(field_document_type_value ='LIC809',1, NULL)),'-') as doc_type_LIC809,  
    IF(count(IF(field_document_type_value ='LIC9099',1, NULL)) >0,count(IF(field_document_type_value ='LIC9099',1, NULL)),'-') as doc_type_LIC9099,  
    IF(count(field_document_f1_value) >0,count(field_document_f1_value),'-')  as substantial_compliance,  
    IF(count(field_document_f2_value) >0,count(field_document_f2_value),'-') as deficiencies_sited,  
    IF(count(field_document_f3_value) >0,count(field_document_f3_value),'-') as admin_outcome_809,  
    IF(count(field_document_f4_value) >0,count(field_document_f4_value),'-') as unfounded,  
    IF(count(field_document_f5_value) >0,count(field_document_f5_value),'-') as substantiated,  
    IF(count(field_document_f6_value) >0,count(field_document_f6_value),'-') as inconclusive,  
    IF(count(field_document_f7_value) >0,count(field_document_f7_value),'-') as further_investigation,  
    IF(count(field_document_f8_value) >0,count(field_document_f8_value),'-') as admin_outcome_9099,  
    IF(count(field_document_type_a_value) >0,count(field_document_type_a_value),'-') as penalty_type_a,  
    IF(count(field_document_type_b_value) >0,count(field_document_type_b_value),'-') as penalty_type_b,  
    IF(sum(field_document_civil_penalties_value) >0,CONCAT('$',sum(field_document_civil_penalties_value)),'-') as total_penalties,  
    IF(count(field_document_noncompliance_value) >0,count(field_document_noncompliance_value),'-') as total_noncompliance  

from rcfe_content_type_facility_document  

where YEAR(field_document_date_value) BETWEEN year(NOW()) -9 AND year(NOW())  
  and field_document_facility_id_value = :facility  

group by doc_year  

2 个答案:

答案 0 :(得分:0)

GROUP您不能SELECT行两次,因此您只能计算一年或一年中的行数。你可以UNION两个SELECT(一个按年分组,第二个没有分组 - 总计)来克服这个限制,但我认为如果有的话,最好从脚本中计算年总结果。< / p>

简化示例:

SELECT by_year.amount, years.date_year FROM

-- generating years pseudo table
(
    SELECT 2008 AS date_year 
    UNION ALL SELECT 2009 
    UNION ALL SELECT 2010 
    UNION ALL SELECT 2011
) AS years

-- joining with yearly stat data
LEFT JOIN 
(
    SELECT SUM(value_field) AS amount, YEAR(date_field) AS date_year FROM data
    GROUP BY YEAR(date_field)
) AS by_year USING(date_year)

-- appending total
UNION ALL SELECT SUM(value_field) AS amount, 'total' AS date_year FROM data

答案 1 :(得分:0)

WITH ROLLUP 是您的朋友: http://dev.mysql.com/doc/refman/5.7/en/group-by-modifiers.html

使用原始查询,只需将其添加到最后一行:

GROUP BY doc_year WITH ROLLUP

这会在查询的结果集中添加最终累积行。

相关问题