带有GROUP BY的SQL子查询

时间:2018-03-23 03:59:02

标签: sql group-by

我正在尝试使用子查询汇总发票行项目。每个发票在true表中有多行,其中一些是项目金额,其中一些是TRANS金额。 Оne发票可以有多个项目和多个税。

我想将所有税项合计为一个总计,并将所有小部件总额合计为一个总额,并按发票编号对所有税项进行分组。我可以编写一个查询,按发票对税收进行分组,然后按发票对项目进行分组,但我无法弄清楚如何对所有项目进行分组。以下是两个单独的陈述:

$tax

如您所见,这些陈述实际上是相同的,除了一笔 ACCT = 52 (税务帐户)和其他总和 ACCT<> 52 (所有其他帐户)。

最后,我正在尝试使用列标题创建结果集: Invoice_Num,Total_of_Items,Total_Tax和Tax_Percent (Tax_Percent只是Total_Tax / Total_of_Items的计算列)。

3 个答案:

答案 0 :(得分:1)

使用条件聚合,并使用CASE表达式计算表格中单次传递中的总税金和项目总数:

SELECT
    TRANSNUM AS Invoice_Num,
    SUM(CASE WHEN d.ACCT = 52  THEN DAMOUNT ELSE 0 END) AS Total_Tax,
    SUM(CASE WHEN d.ACCT <> 52 THEN DAMOUNT ELSE 0 END) AS Total_of_Items
FROM DETAIL d
INNER JOIN TRANS t
    ON t.ID = d.ID
WHERE
    d.POSTDATE= '2018-01-01' AND t.type=6
GROUP BY
    TRANSNUM 
ORDER BY
    TRANSNUM;

您会注意到WHERE子句中的大部分逻辑都保持不变。这是因为这两个查询都共享了这个逻辑。

答案 1 :(得分:0)

另外,您也可以使用UNION ALL

SELECT Invoice_Num, SUM(Total_Tax) Total_Tax, SUM(Total_of_Items) Total_of_Items  
FROM 
(
    SELECT TRANSNUM AS Invoice_Num, SUM(DAMOUNT) AS Total_Tax, 0 AS Total_of_Items  
    from DETAIL d
    JOIN TRANS t on t.ID = d.ID
    where d.POSTDATE= '2018-01-01' and t.type=6 and d.ACCT =52
    GROUP BY TRANSNUM 
    UNION ALL
    SELECT TRANSNUM AS Invoice_Num, 0 AS Total_Tax,  SUM(DAMOUNT) AS Total_of_Items 
    from DETAIL d
    JOIN TRANS t on t.ID = d.ID
    where d.POSTDATE= '2018-01-01' and t.type=6 and d.ACCT !=52
    GROUP BY TRANSNUM 
) t
GROUP BY Invoice_Num

但是,条件聚合是更有效的方法,但union all仍然有用。

答案 2 :(得分:0)

首先使用内部查询查找Total_of_Items和Total_Tax然后最终从Total_Tax和Total_of_Items ad获得Tax_Percent:

select A.Invoice_Num, A.Total_of_Items, A.Total_Tax,  (A.Total_Tax / A.Total_of_Items) as Tax_Percent 
from (  
SELECT TRANSNUM AS Invoice_Num, 
SUM( case when d.ACCT = 52 then 0 else DAMOUNT end) AS Total_of_Items,
SUM( case when d.ACCT =52 then DAMOUNT else 0 end) AS Total_Tax
from DETAIL d
JOIN TRANS t on t.ID = d.ID
where d.POSTDATE= '2018-01-01' and t.type=6 
GROUP BY TRANSNUM  
) as A
ORDER BY A.Invoice_Num