答案 0 :(得分:2)
您可以使用GROUP BY GROUPING SETS
(Postgresql 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;
输出:
请注意,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 | |