MySQL - 复杂查询w / GROUP_CONCAT ...单表

时间:2011-12-20 18:53:43

标签: mysql

我有下表:

id | billingno | location
-------------------------
1  | 9999999   | Toronto
2  | 9999999   | Toronto
3  | 7777777   | Toronto
4  | 7777777   | Quebec

我需要一个可以生成类似内容的查询:

location | total | display
--------------------------
Toronto  | 3     | 9999999 - 2, 7777777 - 1
Quebec   | 1     | 7777777 - 1

因此,它按位置分组,显示该位置的帐号总数,然后显示列列出每个帐号以及它们在该位置的次数。我一直试图写这个,我最接近的尝试就是:

SELECT location, COUNT(*) AS total, GROUP_CONCAT(DISTINCT CAST(CONCAT(CONVERT(billingno,CHAR(16)), ' - ', THIS_COUNT_PART_FOR_EACH_LOCATION_IN_DISPLAY_DOESNT_WORK)AS CHAR)
SEPARATOR ' - ') AS display
FROM table GROUP BY location
ORDER BY COUNT(*) DESC

它给了我所需要的一切,除了我不能为我的生活弄清楚如何计算每个账号的数量。如果我使用COUNT(),它会给我一个关于分组的错误。请帮忙!

哦,我还必须使用convert to char,因此它会显示为文本而不是phpMyAdmin中的BLOB。再次感谢!

3 个答案:

答案 0 :(得分:1)

示例数据:

create table location (
    id int,
    billingno varchar(10),
    location varchar(10)
);

insert into location
select 1, '9999999', 'Toronto' union 
select 2, '9999999', 'Toronto' union 
select 3, '7777777', 'Toronto' union 
select 4, '7777777', 'Quebec' ;

查询:

select 
    location, 
    sum(qty) as total, 
    group_concat(concat(billingno, ' - ', cast(qty as char(7))) 
        order by qty desc separator ', '
    ) as display
from (
    select billingno, location, count(*) as qty
    from location
    group by  billingno, location
) t
group by location
order by total desc

结果:

location    total   display
Toronto     3       9999999 - 2, 7777777 - 1
Quebec      1       7777777 - 1

答案 1 :(得分:0)

这个怎么样,

SELECT table.location, 
       SUM(LocationCount) AS Total,  
       GROUP_CONCAT(CAST(CONCAT(CONVERT(billingno,CHAR(16)), ' - ', THIS_COUNT_PART_FOR_EACH_LOCATION_IN_DISPLAY_DOESNT_WORK)AS CHAR)
SEPARATOR ' - ') AS display
FROM table 
     LEFT JOIN 
     (SELECT location , COUNT(id) AS LocationCount
      FROM table
      GROUP BY location) t on t.location = table.location
GROUP BY location
ORDER BY SUM(LocationCount) DESC

答案 2 :(得分:0)

SELECT location, SUM( total ) AS total, GROUP_CONCAT( CONCAT( billingno, ' - ', billing_count ) ) AS display
FROM (

SELECT location, COUNT( billingno ) AS total, billingno, COUNT( billingno ) AS billing_count
FROM billing
GROUP BY location, billingno
ORDER BY COUNT( * ) DESC 
) AS t
GROUP BY location