MySQL GROUP BY,子串不循环

时间:2012-07-24 12:46:39

标签: mysql group-by substring

我正在尝试按子字符串分组。我只得到一个结果:

Region = Coastal, Value (R) = 1144900.

我应该得到2个结果。

这是我的代码:

SELECT
  DISTINCT SUBSTRING_INDEX(`team_name`, '-', 1) AS 'Region', 
  SUM(`opportunities`.`value`) AS 'Value (R)'
FROM 
  `opportunities` 
  LEFT JOIN cf_type_link_data ON cf_type_link_data.sourceid = opportunities.id
  LEFT JOIN cf_lu_type_fields ON cf_type_link_data.fieldid = cf_lu_type_fields.id
  LEFT JOIN cf_lu_types_fields_dropdown ON cf_type_link_data.`value` = cf_lu_types_fields_dropdown.id AND cf_lu_type_fields.id = cf_lu_types_fields_dropdown.fieldid
  LEFT JOIN `lu_teams` ON `lu_teams`.`contactid` = `opportunities`.`user_allocation`
  LEFT JOIN `teams` ON `teams`.`id` = `lu_teams`.`teamid`
  LEFT JOIN `lu_opportunity_status` ON `lu_opportunity_status`.`id` = `opportunities`.`status`
WHERE 1 
  AND `cf_lu_types_fields_dropdown`.`values` = 'Building Project'
  AND cf_lu_type_fields.fieldname = 'Scaffolding Segment'
  AND (`opportunities`.`expecteddate` >= '2012-01-01' AND `opportunities`.`expecteddate` <= '2012-07-24')
GROUP BY 'Region' 
ORDER BY cf_lu_types_fields_dropdown.`values`;

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您不能在GROUP BY子句

中的select中使用相同的别名

尝试

SELECT DISTINCT SUBSTRING_INDEX(team_name, '-', 1) AS 'Region', 
       SUM(opportunities.value) AS 'Value (R)'....

GROUP BY SUBSTRING_INDEX(team_name, '-', 1)
ORDER BY cf_lu_types_fields_dropdown.values;

答案 1 :(得分:0)

尽量不要在字段标识符中使用引号 -

'地区' - &gt;区域

在您的情况下,您只会在结果数据集中看到一条记录,因为您按字符串'Region'分组,但您应按值分组。