是否可以将我的sql SELECT语句的结果分组,而无需在一个语句中创建临时表并对其进行分组?我有一张表,可以节省信用卡号和借方帐号的借方和贷方金额。 并且为相反的字段放零,我用下面的union select语句做了第一个grouppage我需要根据重复的帐户名称求和 我可以很容易地得到这个或者必须加载临时表吗?我的选择陈述如下
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
我想加入上述结果。
我试图避免使用临时表,但如果这是实现此目的的唯一实用方法,我想了解更多关于以这种方式使用临时表的信息。
我也试过做某种加入和联合,但不满足条件,我也无法弄清楚如何做到这一点。
答案 0 :(得分:2)
如果每个子查询只需要一行,则删除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字段中有异常字符。
答案 1 :(得分:2)
正如您所说的查询有效,我们可以将您的联合查询称为表
( ...... ) 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
答案 2 :(得分:1)
怎么样:
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