0

我需要在查询结果中添加一个额外的列,

该列需要称为百分比,如果col1 == 0则应percent包含NISelsepercent应包含ceil(col2 / col1 * 100)

所以我相信以下应该有效:

IF(col1 = 0, 'NIS', ceil(col2 / col1 * 100)) as percent

但是我遇到了一个问题,因为 col1 和 col2 也是复合的。

COUNT(distinct i.id) as col1
COUNT(distinct q.id) as col2

所以我受到打击

“字段列表”中的未知列“col1”

我可以解决这个问题
IF(COUNT(distinct i.id) = 0, 'NIS', ceil(COUNT(distinct q.id) / COUNT(distinct i.id) * 100)) as percent

但这对我来说似乎是一堆额外的处理,肯定有更好的方法吗?

完整查询

SELECT 
  `t`.*,
  `r`.`name` AS region_name,
  GROUP_CONCAT(DISTINCT p.ptype_id SEPARATOR "|") AS ptype_ids,
  COUNT(DISTINCT q.id) AS quoted,
  COUNT(DISTINCT i.id) AS intended,
  COUNT(DISTINCT qa.id) AS awarded,
  IF(
    intended = 0,
    `"NIS"`,
    CEIL(quoted / intended * 100)
  ) AS percent 
FROM
  (`tradesmen` t) 
  LEFT JOIN `regions` r 
    ON `r`.`id` = `t`.`region_id` 
  LEFT JOIN `quotes` q 
    ON `t`.`id` = `q`.`tradesman_id` 
  LEFT JOIN `quote_intentions` i 
    ON `t`.`id` = `i`.`tradesman_id` 
  LEFT JOIN `quotes` qa 
    ON `q`.`tradesman_id` = `qa`.`tradesman_id` 
    AND qa.accepted = 1 
  LEFT JOIN `ptypes_tradesmen` p 
    ON `p`.`tradesman_id` = `t`.`id` 
GROUP BY `t`.`id` 
LIMIT 20 
4

1 回答 1

1
于 2012-08-28T00:56:22.083 回答