如何在SQL中使用小计

时间:2017-12-06 05:23:03

标签: sql sql-server

我有一张包含以下数据的表格

 CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110     1
  08   test2    0     0      0      1
  05   test3   10     0      0      2
  03   test4    0     0      0      2

我想要一个提供以下输出的查询。 (根据FLAG的小计)

 CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110      1
  08   test2    0     0      0       1
 NULL SUBTOTAL 100    10    110    NULL
  05   test3   10     0      0       2
  03   test4    0     0      0       2
 NULL SUBTOTAL  10    0     10     NULL
TOTAL          110    10    120    NULL

3 个答案:

答案 0 :(得分:2)

  SELECT Code,
         isNULL(NAME,'SUBTOTAL') AS NAME,
         SUM(Total) AS Total,
         SUM(Vat) AS Vat,
         SUM(TotalAmt) AS 
         TotalAmt,
         Flag 
   FROM TABLE GROUP BY ROLLUP(Flag,Code,Name); 

答案 1 :(得分:2)

使用ROLLUP

SELECT
    MAX(CODE) AS CODE,
    NAME,
    MAX(AMOUNT) AS AMOUNT,
    MAX(VAT) AS VAT,
    MAX(TOTALAMT) AS TOTALAMT,
    FLAG
FROM yourTable
GROUP BY
    FLAG, NAME
WITH ROLLUP;

enter image description here

Demo

答案 2 :(得分:-1)

试试这个

;with cte
as
(
 select
  CODE,
  NAME,
  AMOUNT,
  VAT,
  TOTALAMT,
  FLAG
  from t1

  union aLL

  select
  CODE=NULL,
  NAME='SUBTOTAL',
  AMOUNT = SUM(AMOUNT),
  VAT = SUM(VAT),
  TOTALAMT = SUM(TOTALAMT),
  FLAG
  from T1
  GROUP BY FLAG
)
SELECT
*
FROM CTE
ORDER BY FLAG,CODE DESC