为每个子句添加包含总计的摘要行

时间:2016-02-07 09:32:24

标签: sql postgresql

我无法弄清楚如何制作这个sql select语句,我使用PostgreSQL数据库。 这是我的表格:

enter image description here

我想添加一个额外的行显示按性别划分的客户数量:

enter image description here

可以这样做吗?

2 个答案:

答案 0 :(得分:2)

您可以使用GROUP BY GROUPING SETSPostgresql 9.5+):

CREATE TABLE customers(idcust INT, name VARCHAR(100), fkGender INT);
INSERT INTO customers(idcust, name, fkGender)
SELECT 1, 'bob', 3 UNION ALL SELECT 2, 'alice', 3  UNION ALL SELECT 3, 'mikel', 4;

CREATE TABLE gender(IdGender INT, gender VARCHAR(100));
INSERT INTO gender(IdGender, gender) VALUES (3, 'male'),(4,'female');

-------------------------------------------------------------------------------------
SELECT CASE WHEN idcust::text IS NULL THEN 'Total' ELSE idcust::text END AS IdCust,
       CASE WHEN name IS NOT NULL THEN name ELSE COUNT(*)::text END AS name,
       CASE WHEN idcust::text IS NULL THEN '' ELSE gender END AS genderName
FROM customers c
JOIN gender g
  ON c.fkGender = g.idGender
GROUP BY GROUPING SETS((idcust, name, gender), (gender))
ORDER BY gender DESC, idcust;

输出:

enter image description here

请注意,idcust可能是INT,因此要在该列中获取Total,您必须先将其转换为文字。

答案 1 :(得分:0)

对于9.5之前的版本,您可以创建一个aditional列group_id,并且始终注意数据类型,因此不要混合文本和数字。

注意:但请注意,对于这类事情,您通常会将两个SELECT分开并将它们连接到前端,以便您可以应用正确的格式/样式

<强> SQL Fiddle DEMO

SELECT idcust::text, name, gender
FROM 
(
    SELECT 2*fkGender as  group_id,
           idcust::text, name, gender
    FROM customers c
    JOIN gender g
      ON c.fkGender = g.idGender
    UNION ALL 
    SELECT 2*fkGender + 1 as group_id,
           'Total'::text as idcust,
           COUNT(*)::text as name,
           '' as gender
    FROM  customers c
    GROUP BY group_id, fkGender
) T
ORDER BY group_id, idcust

<强>输出

| idcust |  name | gender |
|--------|-------|--------|
|      1 |   bob |   male |
|      2 | alice |   male |
|  Total |     2 |        |
|      3 | mikel | female |
|  Total |     1 |        |