使用 SQL 将 Oracle 中的 2 行分组为 1 行

发布于 2024-09-30 14:39:46 字数 319 浏览 9 评论 0原文

我有一个表,其中包含数据,就像

state   total   

A       3   

B       6

C       2 

D       7

E       4

我需要从中生成一个总共包含 A 和 A 的表一样。 B(真)一起和 C、D、E(假)一起 有

Result Table

Status     Total

True        9 (sum of A and B )

False       13 (sum of C, D, E)

什么想法如何使用 SQL 来做到这一点?我在 Oracle 中这样做

I have a table which has data like

state   total   

A       3   

B       6

C       2 

D       7

E       4

I need to generate a table from this that has total of A & B (true) together and C, D, E (False) together

Result Table

Status     Total

True        9 (sum of A and B )

False       13 (sum of C, D, E)

Any ideas how to do this using SQL? I am doing this in Oracle

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

比忠 2024-10-07 14:39:46
SELECT  nstate, SUM(total)
FROM    (
        SELECT  DECODE(state, 'A', 'True', 'B', 'True', 'False') AS nstate, total
        FROM    mytable
        )
GROUP BY
        nstate
SELECT  nstate, SUM(total)
FROM    (
        SELECT  DECODE(state, 'A', 'True', 'B', 'True', 'False') AS nstate, total
        FROM    mytable
        )
GROUP BY
        nstate
寄人书 2024-10-07 14:39:46

我会使用 UNION 查询

SELECT 'True' AS Status, SUM(total) AS Total
FROM table
WHERE state IN ('A', 'B')
UNION
SELECT 'False' AS STATUS, SUM(total) AS Total
FROM table
WHERE state IN ('C', 'D', 'E')
ORDER BY Status DESC;

您可能需要按每个查询的状态进行分组,但我不确定,因为该列是虚拟/静态/标量

I'd use a UNION query

SELECT 'True' AS Status, SUM(total) AS Total
FROM table
WHERE state IN ('A', 'B')
UNION
SELECT 'False' AS STATUS, SUM(total) AS Total
FROM table
WHERE state IN ('C', 'D', 'E')
ORDER BY Status DESC;

You may need to group by Status on each query but I'm not sure as the column is virtual / static / scalar

风月客 2024-10-07 14:39:46

我喜欢 CASE - 我认为它比 DECODE 更容易解释:

CREATE TABLE RESULT_TABLE AS
  SELECT STATE, SUM(TOTAL) AS TOTAL
    FROM (SELECT CASE STATE
                    WHEN 'A' THEN 'True'
                    WHEN 'B' THEN 'True'
                    ELSE 'False'
                 END AS STATE,
                 TOTAL
            FROM MY_TABLE) 
  GROUP BY STATE;

分享和享受。

I like CASE - I think it's easier to interpret than DECODE:

CREATE TABLE RESULT_TABLE AS
  SELECT STATE, SUM(TOTAL) AS TOTAL
    FROM (SELECT CASE STATE
                    WHEN 'A' THEN 'True'
                    WHEN 'B' THEN 'True'
                    ELSE 'False'
                 END AS STATE,
                 TOTAL
            FROM MY_TABLE) 
  GROUP BY STATE;

Share and enjoy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文