如何在SQL中使用特定条件求和多行

时间:2019-10-01 02:06:45

标签: sql sql-server

我有一个查询,可以按以下产品汇总余额:

SELECT BCM_CORPORATION_NUMBER, BCM_PRODUCT
  SUM(BCM_TOT_NEW_BAL) AS TOTAL_BALANCE
FROM BCM_IN
GROUP BY BCM_CORPORATION_NUMBER, BCM_PRODUCT
ORDER BY BCM_CORPORATION_NUMBER ASC;

结果

Corp.        PRODUCT.    TOTAL_BALANCE
002030.      VCLBUS.       3000
002030.      VGOBUS.       1000
002030.      VCL000.       4000

我想将“ VCLBUS”和“ VGOBUS”产品的总数相加,以总计显示4000,而没有VCL000产品。

看起来像这样: 公司产品。 TOTAL_BALANCE     002030。VCLBUS/ VGOBUS。 4000     002030。VCL000。 4000

3 个答案:

答案 0 :(得分:1)

这是您想要的吗?

SELECT BCM_CORPORATION_NUMBER, SUM(BCM_TOT_NEW_BAL) AS TOTAL_BALANCE
FROM BCM_IN
WHERE BCM_PRODUCT IN ('VCLBUS', 'VGOBUS')
GROUP BY BCM_CORPORATION_NUMBER
ORDER BY BCM_CORPORATION_NUMBER ASC;

或者您可以:

WHERE BCM_PRODUCT <> 'VCL000'

答案 1 :(得分:0)

这是您的查询。

SELECT t1.BCM_CORPORATION_NUMBER, t1.BCM_PRODUCT, SUM(t1.TOTAL_BALANCE) 
FROM (SELECT BCM_CORPORATION_NUMBER, BCM_PRODUCT
     SUM(BCM_TOT_NEW_BAL) AS TOTAL_BALANCE, 
     FROM BCM_IN
     GROUP BY BCM_CORPORATION_NUMBER, BCM_PRODUCT
     ) t1
WHERE t1.BCM_PRODUCT IN ('VCLBUS', 'VGOBUS')
ORDER BY t1.BCM_CORPORATION_NUMBER ASC

SELECT BCM_CORPORATION_NUMBER
    , BCM_PRODUCT
    , BCM_TOT_NEW_BAL
    , SUM(BCM_TOT_NEW_BAL) AS TOTAL_BALANCE
FROM BCM_IN
WHERE BCM_PRODUCT IN ('VCLBUS', 'VGOBUS')
GROUP BY BCM_CORPORATION_NUMBER, BCM_PRODUCT, BCM_TOT_NEW_BAL
ORDER BY BCM_CORPORATION_NUMBER ASC;

答案 2 :(得分:0)

假设您的Output在临时表或CTE

create table #Output(Corp varchar(15),PRODUCT varchar(50),TOTAL_BALANCE int)



insert into #Output 
SELECT BCM_CORPORATION_NUMBER, BCM_PRODUCT
  SUM(BCM_TOT_NEW_BAL) AS TOTAL_BALANCE
FROM BCM_IN
GROUP BY BCM_CORPORATION_NUMBER, BCM_PRODUCT
;

OR

;With OutPutCTE
(
SELECT BCM_CORPORATION_NUMBER, BCM_PRODUCT
  SUM(BCM_TOT_NEW_BAL) AS TOTAL_BALANCE
FROM BCM_IN
GROUP BY BCM_CORPORATION_NUMBER, BCM_PRODUCT
--ORDER BY BCM_CORPORATION_NUMBER ASC
)

假设您想分组'VCLBUS', 'VGOBUS' 同样,您将希望对GROUP个其他乘积求和,并相应地对SUM求和。

创建#temp表并根据其组存储产品

create table #GroupType(PRODUCT varchar(50),groupid int)
insert into #GroupType values
 ('VCLBUS.',1)
,('VGOBUS.',1)
,('VCL000.',2)

select o.* 
,sum(TOTAL_BALANCE)over(partition by g.groupid )Group_TOTAL_BALANCE 
from #Output O
inner join #GroupType G on o.PRODUCT=g.PRODUCT

我认为您可以得到想要的任何输出。