Mysql根据多列选择唯一记录,仅显示组和总和

时间:2018-03-20 08:53:12

标签: mysql

您好我正在尝试查询在代码,金额和状态上包含多个重复项的表如果我只根据client_group名称获取结果组并获得该组下的金额总和,我将如何执行此操作< / p>

SELECT `client`.`client_group` 
,  FORMAT(SUM(`Data_result`.`Data_result_amount` ),2) as sum
FROM
  `qwer`.`Data_result`
  INNER JOIN `qwer`.`Data` 
      ON (`Data_result`.`Data_result_lead` = `Data`.`Data_id`)
  INNER JOIN `qwer`.`Data_status` 
      ON (`Data_result`.`Data_result_status_id` = `Data_status`.`Data_status_id`)
  INNER JOIN `qwer`.`client` 
      ON (`Data`.`Data_client_id` = `client`.`client_id`)
WHERE `Data_status`.`Data_status_name` IN ('PAID') AND  MONTH(`Data_result`.`result_ts`) = MONTH(CURRENT_DATE())
AND YEAR(`Data_result`.`result_ts`) = YEAR(CURRENT_DATE())
GROUP BY `client`.`client_group`

所述查询的结果:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

在运行&#39;之前尝试区分。检查这是否能解决您的问题

    SELECT `client_group` ,  FORMAT(SUM(`Data_result_amount` ),2) as sum from (
    SELECT DISTINCT `client`.`client_group` , `Data_result`.`Data_result_amount` 
    FROM
      `qwer`.`Data_result`
      INNER JOIN `qwer`.`Data` 
          ON (`Data_result`.`Data_result_lead` = `Data`.`Data_id`)
      INNER JOIN `qwer`.`Data_status` 
          ON (`Data_result`.`Data_result_status_id` = `Data_status`.`Data_status_id`)
      INNER JOIN `qwer`.`client` 
          ON (`Data`.`Data_client_id` = `client`.`client_id`)
    WHERE `Data_status`.`Data_status_name` IN ('PAID') AND  MONTH(`Data_result`.`result_ts`) = MONTH(CURRENT_DATE())
    AND YEAR(`Data_result`.`result_ts`) = YEAR(CURRENT_DATE())
    ) T
    GROUP BY `client_group`

您可以在http://sqlfiddle.com/#!9/36a3f8/6

查看查询