使用两个不同的列生成摘要

b0zn9rqh  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(341)

我正在尝试生成销售组针对特定产品的呼叫总数摘要。但是,产品列在p1或p2中,因为一次通话最多可以提到两种产品。我的密码是

SELECT  SALESFORCE_ID,P1 AS PRODUCT,SUM(Calls) as Calls 
            FROM Calls
                GROUP BY SALESFORCE_ID, P1
UNION
SELECT SALESFORCE_ID,P2,SUM(Calls) as Calls
            FROM Calls
                WHERE P2 <> ''
                GROUP BY SALESFORCE_ID, P2

它生成以下结果

SALESFORCE_ID                                      PRODUCT                                            Calls
-------------------------------------------------- -------------------------------------------------- -----------
SALESFORCE_HP                                      PRODUCT_E                                          18111
SALESFORCE_HP                                      PRODUCT_E                                          83925
SALESFORCE_HP                                      PRODUCT_S                                          17931
SALESFORCE_HP                                      PRODUCT_S                                          87390
SALESFORCE_SP                                      PRODUCT_M                                          382230
SALESFORCE_SP                                      PRODUCT_W                                          159534
SALESFORCE_SSTR                                    PRODUCT_E                                          2751
SALESFORCE_SSTR                                    PRODUCT_M                                          3276
SALESFORCE_SSTR                                    PRODUCT_S                                          4314
SALESFORCE_SSTR                                    PRODUCT_W                                          948
SALESFORCE_STR                                     PRODUCT_M                                          10347
SALESFORCE_STR                                     PRODUCT_M                                          45963
SALESFORCE_STR                                     PRODUCT_S                                          22263
SALESFORCE_STR                                     PRODUCT_S                                          23787

在销售组和产品相等的情况下,如何求和结果?

wvmv3b1j

wvmv3b1j1#

在销售组和产品相等的情况下,如何求和结果?
您可以添加另一个聚合级别:

select salesforce_id, product, sum(calls) calls
from (
    select salesforce_id,p1 as product,sum(calls) as calls 
    from calls
    group by salesforce_id, p1
    union all
    select salesforce_id,p2,sum(calls) as calls
    from calls
    where p2 <> ''
    group by salesforce_id, p2
) t
group by salesforce_id, product

在我看来,使用 union (用于消除重复结果): union all 已经足够好了,并且对数据库所做的工作更少。

nkcskrwz

nkcskrwz2#

你可能需要这个,因为更优雅和性能的方式

WITH TotalCalls AS
(SELECT SALESFORCE_ID,
       P1 AS PRODUCT,
       Calls
FROM Calls
UNION ALL
SELECT SALESFORCE_ID,
       P2 AS PRODUCT,
       Calls
FROM Calls
WHERE P2 <> '')

SELECT SALESFORCE_ID, PRODUCT, SUM(Calls) AS Calls
FROM TotalCalls
GROUP BY SALESFORCE_ID, PRODUCT

相关问题