#1055-SELECT列表的表达式#2不在GROUP BY子句中,并且包含未聚合的列'osunemonitor.r.entry_date'

时间:2019-02-09 01:56:13

标签: mysql sql

我正在尝试按ward_name分组,这是我唯一需要分组的内容,但出现此错误:

  

\#1055-SELECT列表的表达式#2不在GROUP BY子句中,并且包含未聚合的列'osunemonitor.r.entry_date',该列在功能上不依赖于GROUP BY子句中的列;这与sql_mode = only_full_group_by

不兼容

在我的查询中,如何仅按ward_name将其分组?

我的查询:

SELECT 
    pu.pu_ward_name, 
    entry_date,
    pu.o_code,
    pu.pu_ward_name,
    pu.pu_lga_name,
    pu.pu_code,
    pu.pu_ward_code,
    pu.pu_lga_code,
    pu.pu_voters_reg_count, 
    SUM(total_vote_cast) AS total_vote_cast,
    SUM(apc_total_vote) AS apc_total_vote,
    SUM(pdp_total_vote) AS pdp_total_vote,
    SUM(adp) AS adp, ward_name
FROM 
    post_election_info r 
    LEFT JOIN polling_unit pu ON r.ward_name = pu.pu_ward_name 
WHERE lga_name = 'BORIPE'
GROUP BY 
    pu.pu_ward_name

1 个答案:

答案 0 :(得分:1)

每个非聚合列都必须出现在GROUP BY子句中。这是ANSI SQL的标准,尽管MySQL的较早版本对此比较松懈。

考虑一下:如果您SELECT列而不是GROUP BY,那么RDBMS如何可靠地选择应显示组中的哪个值?

可能的解决方案包括:

  • 将所有其他未聚合的列添加到GROUP BY子句
  • 对除pu_ward_name以外的所有列使用聚合函数。例如,MAX()和MIN()是字符串友好的(不同于SUM())。

第一个解决方案:

SELECT 
    pu.pu_ward_name, 
    entry_date,
    pu.o_code,
    pu.pu_lga_name,
    pu.pu_code,
    pu.pu_ward_code,
    pu.pu_lga_code,
    pu.pu_voters_reg_count, 
    SUM(total_vote_cast) AS total_vote_cast,
    SUM(apc_total_vote)  AS apc_total_vote,
    SUM(pdp_total_vote)  AS pdp_total_vote,
    SUM(adp) AS adp
FROM 
    post_election_info r 
    LEFT JOIN polling_unit pu ON r.ward_name = pu.pu_ward_name 
WHERE lga_name = 'BORIPE'
GROUP BY 
    pu.pu_ward_name, 
    entry_date,
    pu.o_code,
    pu.pu_lga_name,
    pu.pu_code,
    pu.pu_ward_code,
    pu.pu_lga_code,
    pu.pu_voters_reg_count

第二个解决方案:

SELECT 
    pu.pu_ward_name, 
    MAX(entry_date)             AS entry_date,
    MAX(pu.o_code)              AS o_code,
    MAX(pu.pu_lga_name)         AS pu_lga_name,
    MAX(pu.pu_code)             AS pu_code,
    MAX(pu.pu_ward_code)        AS pu_ward_code,
    MAX(pu.pu_lga_code)         AS pu_lga_code,
    MAX(pu.pu_voters_reg_count) AS pu_voters_reg_count, 
    SUM(total_vote_cast)        AS total_vote_cast,
    SUM(apc_total_vote)         AS apc_total_vote,
    SUM(pdp_total_vote)         AS pdp_total_vote,
    SUM(adp)                    AS adp
FROM 
    post_election_info r 
    LEFT JOIN polling_unit pu ON r.ward_name = pu.pu_ward_name 
WHERE lga_name = 'BORIPE'
GROUP BY 
    pu.pu_ward_name