【问题标题】:db2 aggregates and case when conditions giving repeated values and incorrect datadb2 聚合和 case when 条件给出重复值和不正确的数据
【发布时间】:2023-03-17 04:52:01
【问题描述】:

我有一个简单的查询,其中包含正确返回产品信息的连接:

select
            t1.category,
            t1.color,
            t1.size,
            t2.aisle

from infoTable t1

inner join locationTable t2 on t1.aisleNumber = t2.aisleNumber;

返回

category  |  color  |  size  |  aisle
--------------------------------------
A             Red       S        F12
B             Blue      M        G18
C             Green     L        H9
D             Yellow    XL       D19

到目前为止,一切都很好。

现在,我想加入一个表格,告诉我哪些商店有每种产品,每种产品有多少。我正在另一个表中的每个商店手动检查这些产品,以确保我的数据准确无误。

select
            t1.category,
            t1.color,
            t1.size,
            t2.aisle,
            count(case when t3.storeNumber = 11 then 1 else 0 end) as storeNumber11
            count(case when t3.storeNumber = 31 then 1 else 0 end) as storeNumber31
            count(case when t3.storeNumber = 41 then 1 else 0 end) as storeNumber41

from infoTable t1

inner join locationTable t2 on t1.aisleNumber = t2.aisleNumber
inner join storeTable t3    on t1.category = t3.category and t1.color = t3.color and t1.size = t3.size

group by t1.category,t1.color,t1.size,t2.aisle,t3.storeNumber

我很接近,但结果不正确。我明白了:

    category  |  color  |  size  |  aisle  |  storeNumber11 |  storeNumber31  |  storeNumber41
    --------------------------------------------------------------------------------------------
    A             Red       S        F12         17                 17                  17
    B             Blue      M        G18         12                 12                  12
    C             Green     L        H9          14                 14                  14
    D             Yellow    XL       D19         16                 16                  16

在手动检查第一行的 storeNumber11 应为 17,但 31 和 41 为 0 后,我知道一个事实。第二行的 storeNumber11 应为 0,而 storeNumber31 为 12。

所以我没有得到零并且只得到相同的值重复这一事实表明,有些事情显然是错误的。否则,我将获得正确的行数和信息,但是如果满足 t3 的连接,我该如何解决这个问题以正确地只计算那些商店编号?

【问题讨论】:

    标签: sql db2-400


    【解决方案1】:

    使用sum(),而不是count()

    select
            t1.category,
            t1.color,
            t1.size,
            t2.aisle,
            sum(case when t3.storeNumber = 11 then 1 else 0 end) as storeNumber11
            sum(case when t3.storeNumber = 31 then 1 else 0 end) as storeNumber31
            sum(case when t3.storeNumber = 41 then 1 else 0 end) as storeNumber41
    . . . 
    

    count(<x>) 计算非NULL 值的数量。 01 一样非NULL

    【讨论】:

      猜你喜欢
      • 2018-04-21
      • 2021-05-08
      • 1970-01-01
      • 2018-04-04
      • 2014-07-15
      • 2020-08-23
      • 2011-04-17
      • 2019-10-16
      • 1970-01-01
      相关资源
      最近更新 更多