1

使用 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  
4

2 回答 2

0

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

简化示例:

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
于 2012-06-20T06:32:48.463 回答
0

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

使用您的原始查询并将其添加到最后一行:

GROUP BY doc_year WITH ROLLUP

这将为您的查询结果集添加一个最终累积行。

于 2016-01-07T23:23:38.057 回答