字符串的小计和总计

时间:2013-11-12 09:33:02

标签: mysql sql

我有一个名为abc的表,有2列 - 城市和房屋。(我使用的是MYSQL 6.0)

 houses            city
    A               P
    B               Q
    C               P
    D               R
    E               P
    F               S
    G               S

我想以这种方式输出:

houses             city
A                   p                  
C                   p
E                   p
noofhouses:         3

B                   Q
noofhouses:         1 

D                   R
noofhouses:         1

F                   S
G                   S
noofhouses:         2
totalhouses         7

所以基本上我想要一份房屋名单而不是。在一个城市的房子。 那可能吗?? 请帮忙。 提前谢谢。

3 个答案:

答案 0 :(得分:1)

如果您确实希望在SQL中完全执行此操作,则可以使用:

SELECT IFNULL(Title, aHouse) AS House, IFNULL(Total, aCity) AS City
FROM
(
    SELECT House AS aHouse, City AS aCity, NULL AS Total, NULL AS Title
    FROM @abc 
    UNION 
    SELECT NULL AS aHouse, City AS aCity, CAST(COUNT(House)  AS CHAR(4)) AS Total, 'noofhouses:' AS Title
    FROM @abc
    GROUP BY City
    UNION 
    SELECT NULL AS aHouse, 'zzzzz' AS aCity, CAST(COUNT(House)  AS CHAR(4)) AS Total, 'total:' AS Title
    FROM @abc
) a
ORDER BY aCity, Title, aHouse 

输出:

House       City
----------- ----
A           P   
C           P   
E           P   
noofhouses: 3   
B           Q   
noofhouses: 1   
D           R   
noofhouses: 1   
F           S   
G           S   
noofhouses: 2   
total:      7   

SQLFiddle

答案 1 :(得分:1)

两种可能性:

select
group_concat(houses), count(*), city
from
Table1
group by city;

select a.houses, a.city, noofhouses
from Table1 a
inner join (
select
count(*) as noofhouses, city
from Table1
group by city
) b on a.city = b.city
order by a.city, noofhouses desc, a.houses;

它不完全是您的输出,但其中的信息是相同的。数据库不能很好地格式化数据。这应该在应用层中完成。

答案 2 :(得分:1)

使用WITH ROLLUP选项自动创建小计。将它放在子查询中,并使用外部查询重新格式化结果。

SELECT CASE WHEN city IS NULL THEN 'totalhouses'
            WHEN houses IS NULL THEN 'noofhouses'
            ELSE houses
       END houses,
       CASE WHEN houses IS NULL then num
            ELSE city
       END city
FROM (
    SELECT houses, city, count(*) num
    FROM yourTable
    GROUP BY city, houses WITH ROLLUP) x

FIDDLE