-3

我有一个名为 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

所以基本上我想要一个房子的名字列表,没有。一座城市的房子。那可能吗??请帮忙。提前致谢。

4

3 回答 3

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

小提琴

于 2013-11-12T09:58:17.653 回答
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

于 2013-11-12T09:45:31.480 回答
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;

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

于 2013-11-12T09:47:48.690 回答