表格数据:
NAME RS
A 10
A 20
A 30
B 15
B 5
B 10
C 70
C 30
预期产出:
A -- column name
10
20
30
60 -- total of A
B
15
5
10
30 -- total of B
C
70
30
100 -- total of C
到目前为止,我已经尝试过:
UNION ALL
没有UNION ALL
还有其他最简单的解决方案吗?
答案 0 :(得分:1)
使用纯SQL在单个查询中执行此操作:
SELECT unnest(arr)
FROM (
SELECT ARRAY[name] || array_agg(rs::text) || sum(rs)::text AS arr
FROM tbl
GROUP BY name
) sub
ORDER BY arr[1];
与@WingedPanther发布的内容类似,但任何名称都是干净且安全的。
返回:
A
10
20
30
60
B
15
15
C
70
30
100
或者:
WITH cte AS (
SELECT name, sum(RS)::text AS sum_rs
FROM tbl
GROUP BY 1
)
SELECT unicol
FROM (
SELECT name AS unicol, name AS order1, 1 AS order2 FROM cte
UNION ALL
SELECT sum_rs, name, 2 FROM cte
) sub
ORDER BY order1, order2;
返回:
A
60
B
15
C
100
或者只是从CTE发送结果,然后完成客户端。
答案 1 :(得分:1)
试试这个
select unnest(string_to_array( name ||','||rs||','||sum, ',')) AS elem
from (
select name
,string_agg(rs::text,',') rs
,sum(rs)
from tbl
group by name
)t
如果您想在结果中使用
打印Total Of
select unnest(string_to_array( name ||','||rs||','||sum, ',')) AS elem
from (
select name
,string_agg(rs::text,',') rs
,'Total Of '||name||' '|| sum(rs) sum
from tbl
group by name
)t
答案 2 :(得分:0)
不是100%肯定你之后的事情,但听起来你只是想要这个:
Select name, Sum(RS)
from sometable
group by name
答案 3 :(得分:-2)
试试这个:
DECLARE @t TABLE(Name NVARCHAR(MAX), RS INT)
INSERT INTO @t VALUES
('A', 10),
('A', 20),
('A', 30),
('B', 15),
('C', 70),
('C', 30)
使用UNION
SELECT Name, RS, 0 AS OrderBit FROM @t
UNION ALL
SELECT Name, SUM(RS) AS Total, 1 AS OrderBit FROM @t
GROUP BY Name
ORDER BY Name, OrderBit
没有联盟:
SELECT Name, SUM(RS) AS RS FROM @t
GROUP BY GROUPING SETS((Name), (Name, RS))