select * from(从表中选择count(*))

时间:2016-01-09 16:38:49

标签: sql select

表:安装

+ id    + id_city   +   name    + sts   +
-------------------------------------------
+ 1     +   1       +   jerry   +   1   +
+ 2     +   1       +   david   +   0   +
+ 3     +   2       +   will    +   1   +
+ 4     +   3       +   nanda   +   2   +
+ 5     +   3       +   maya    +   0   +
+ 6     +   4       +   maya    +   2   +
来自sts列的

instractions

0 --> pending
1 --> success
2 --> fail

表:城市

+ id_city   +   nm_city     +
-----------------------------
+   1       +   california  +
+   2       +   alaska      +
+   3       +   colorado    +
+   4       +   georgia     +
+   5       +   hawaii      +
+   6       +   lowa        +

我想从表安装中添加与city表结合的行,下表是所需的结果

+   nm_city     + id_city   +   suc + fail  +   pending +
----------------------------------------------------------
+   california  +   1       +   2   +   0   +   1
+   alaska      +   2       +   1   +   0   +   0
+   colorado    +   3       +   0   +   1   +   1
+   georgia     +   4       +   0   +   1   +   0

我尝试使用以下查询,但SUC列,FAIL和PENDING的总和不适合

select * from
(select w.nm_city,i.id_city from installation i join city w on i.id_city=w.id_city group by i.id_city) WIL,
(select count(*) as suc from installation where sts=1) SUC,
(select count(*) as fail from installation where sts=2) FAIL,
(select count(*) as pen from installation where sts=0) PEN

请帮帮我

3 个答案:

答案 0 :(得分:2)

您可以使用sum + case执行此操作:

SELECT
    w.nm_city,
    i.id_city,
    sum(case when sts = 1 then 1 else 0 end),
    sum(case when sts = 2 then 1 else 0 end),
    sum(case when sts = 0 then 1 else 0 end)
FROM installation i
JOIN city w
    ON i.id_city = w.id_city
GROUP BY i.id_city

顺便说一下。你的城市不是城市,而是州。

答案 1 :(得分:0)

你需要SUM over CASE:

SELECT
        i.id_city,
        w.nm_city,
        SUM(CASE WHEN sts=0 THEN 1 ELSE 0) as pending,
        SUM(CASE WHEN sts=1 THEN 1 ELSE 0) as success,
        SUM(CASE WHEN sts=2 THEN 1 ELSE 0) as fail
    FROM
        installation I
        JOIN city W ON i.id_city = w.id_city
    GROUP BY
        i.id_city,
        w.nm_city

虽然这必须在mysql和sql-server中工作。将来请直接指定您的DBMS。

答案 2 :(得分:0)

使用条件聚合:

SELECT c.id_city, c.nm_city,
   SUM(sts=0) AS pending,
   SUM(sts=1) AS success,
   SUM(sts=2) AS fail
FROM city c
JOIN instalation i
  ON c.id_city = i.id_city
GROUP BY id_city, nm_city

SqlFiddleDemo

输出:

╔══════════╦═════════════╦══════════╦══════════╦══════╗
║ id_city  ║  nm_city    ║ pending  ║ success  ║ fail ║
╠══════════╬═════════════╬══════════╬══════════╬══════╣
║       1  ║ california  ║       1  ║       1  ║    0 ║
║       2  ║ alaska      ║       0  ║       1  ║    0 ║
║       3  ║ colorado    ║       1  ║       0  ║    1 ║
║       4  ║ georgia     ║       0  ║       0  ║    1 ║
╚══════════╩═════════════╩══════════╩══════════╩══════╝

原始问题由MySQL标记,答案是针对MySQL的。如果它应该在不同的RDBMS上使用CASE语句。