分组和计算列中的多个值

时间:2015-11-04 00:14:45

标签: mysql sql sql-like

我试图生成一份报告,说明我们每天在每个城市开展的工作量,并显示我们从哪里获得这份工作。

我有一个包含多个郊区的列(大约300-350)。这些是两个城市的郊区。我想将这些郊区分组到适当的城市并显示计数。

我在想这样的事情:

Site_Suburb LIKE '%Suburb1%' OR LIKE '%Suburb2%' AS `City1` 
Site_Suburb LIKE '%Suburb3%' OR LIKE '%Suburb4%' AS `City2 

(只是粗略的伪代码,以帮助给你一个想法..)

总体而言,我需要将报告发送至GROUP BY DateCityJob Source

到目前为止我有这个问题:

SELECT
from_unixtime(`reservations`.`created`) AS `formatted_date`,
`reservations`.`start_date` AS `start_date`,
`reservations`.`site_suburb` AS `site_suburb`,
`reservations`.`job_source` AS `job_source`,

DATE(FROM_UNIXTIME(`reservations`.`created`)) AS date,

COUNT(`reservations`.`created`) as group_by_count from `reservations`

GROUP BY
DATE(FROM_UNIXTIME(`reservations`.`created`)),
`reservations`.`site_suburb`,
`reservations`.`job_source`

order by from_unixtime(`reservations`.`created`) desc

提前致谢^ _ ^

2 个答案:

答案 0 :(得分:0)

select
    case
         when Site_Suburb LIKE '%Suburb1%' OR Site_Suburb LIKE '%Suburb2%' AS `City1` 
         when Site_Suburb LIKE '%Suburb3%' OR Site_Suburb LIKE '%Suburb4%' AS `City2 

    else site_suburb end Suburb
    ,job_source
    ,DATE(FROM_UNIXTIME(`reservations`.`created`)) AS date
    ,count(*) as jobs

from 
    reservations

group by
   case
         when Site_Suburb LIKE '%Suburb1%' OR LIKE '%Suburb2%' AS `City1` 
         when Site_Suburb LIKE '%Suburb3%' OR LIKE '%Suburb4%' AS `City2 

    else site_suburb end 
  ,job_source
  ,DATE(FROM_UNIXTIME(`reservations`.`created`))

答案 1 :(得分:0)

也许你想要的是in

select (case when Site_Suburb in ('Suburb1', 'Suburb2') then 'City1'
             when Site_Suburb in ('Suburb3', 'Suburb4') then 'City2'
             else site_suburb
        end) Suburb,
       job_source,
       DATE(FROM_UNIXTIME(`reservations`.`created`)) AS date,
       count(*) as jobs
from reservations
group by suburb, job_source, DATE(FROM_UNIXTIME(`reservations`.`created`));

这显然不适用于所有情况,因为in会查找没有通配符的完全匹配。

实际上,处理此问题的最佳方法是使用一列中的site_suburb和另一列中的city查找表。