嵌套联合 select 语句

nested union select statement

是否可以在不创建临时 table 的情况下对我的 sql SELECT 语句的结果进行分组以在一个语句中求和和分组?我有一个 table 保存贷方帐号和借方帐号的借方和贷方总金额。 并为相反的字段置零,我用下面的 union select 语句创建了第一个组页,我需要根据重复的帐户名称对输出求和 我可以很容易地得到它还是必须加载它的温度 table?我的 select 声明如下

select  journal_drname  AS ACCNAME, sum(amount) AS DEBT,0 as CREDIT
FROM JOURNAL GROUP BY journal_drname 
 UNION select  journal_crname  AS ACCNAME, 0 as DEBT,sum(amount) AS   
 CREDIT,
 FROM JOURNAL GROUP BY journal_crname

返回数据如下:

ACCNAME      DEBIT     CREDIT
--------   -------     ------
CASH        0           1,000
CASH        900          0
CASH        300          0
BANK        200          0
BANK        400          0

我可以把上面的总结分组如下吗:

ACCNAME      DEBIT     CREDIT
--------   -------     ------
CASH        200          0
BANK        600          0

而且我想把这些要剪的结果加入到上面。

我试图避免使用临时 table,但如果这是唯一可行的方法,我想了解更多有关以这种方式使用临时 table 的信息.

我也试过做一些连接和联合,但不满足条件,我也不知道该怎么做。

如果每个子查询只需要一行,则删除 group by:

select  'CASH' as ACCNAME, sum(amount) AS DEBT, 0 as CREDIT
FROM JOURNAL 
UNION ALL
select  'BANK' as ACCNAME, 0 as DEBT, sum(amount) AS  CREDIT
FROM JOURNAL;

(注意:ACCNAME 值可能会颠倒。)

重要提示:对于此类查询,您应该使用 UNION ALL 而不是 UNION。没有理由承担删除重复项的开销,除非您打算删除重复项。

此外,您的原始查询应该有效,除非 accname 字段中有不寻常的字符。

如您所说,您的查询有效,让我们将您的联合查询称为 table

( ...... ) myTable

然后只需创建一个子查询即可完成最后一步

SELECT ACCNAME,
       CASE WHEN SUM(CREDIT - DEBT) < 0 THEN - SUM(CREDIT - DEBT)
            ELSE 0
       END DEBT,
       CASE WHEN SUM(CREDIT - DEBT) > 0 THEN   SUM(CREDIT - DEBT)
            ELSE 0
       END CREDIT
FROM ( ...... ) myTable
GROUP BY ACCNAME

怎么样:

select ACCNAME, 
    CASE WHEN sum(DEBT)>sum(CREDIT) THEN sum(DEBT)-sum(CREDIT) ELSE 0 AS DEBT, 
    CASE WHEN sum(DEBT)<sum(CREDIT) THEN sum(CREDIT)-sum(DEBT) ELSE 0 AS CREDIT 
FROM (
    select  journal_drname  AS ACCNAME, 
        sum(amount) AS DEBT,
        0 as CREDIT
    FROM JOURNAL GROUP BY journal_drname 
UNION 
    select journal_crname  AS ACCNAME, 
        0 as DEBT,
        sum(amount) AS CREDIT,
 FROM JOURNAL GROUP BY journal_crname
) group by ACCNAME