【问题标题】:SQL Server rows count return with inner join more than once in same tableSQL Server 行计数在同一个表中多次返回内部联接
【发布时间】:2018-10-29 16:54:36
【问题描述】:

我有这个代码

select 
    count(cat_item_tb.item_id),
    count(t.item_id) 
from 
    cat_tb 
inner join
    item_tb on cat_tb.cat_id = item_tb.cat_id
inner join
    cat_item_tb on item_tb.item_id = cat_item_tb.item_id and t.ss = 0
inner join
    cat_item_tb t on item_tb.item_id = t.item_id and t.ss = 1

我只需要返回没有重复的值。在过去的代码中,每次计数都必须返回 7,但它返回 49,这两个 count() 相互影响。我使用 distinct 但它没有返回正确的计数,因为表中有 (item_id) 不止一次

非常感谢

【问题讨论】:

  • 样本和期望的结果会很有帮助。
  • 当连接的两侧有多个具有相同值的行时,这是预期的。所以这是你的数据而不是查询。
  • 请注意 7 * 7 = 49 ;-)

标签: sql sql-server count


【解决方案1】:

我相信你想写这样的东西:

select 
    count(c1.item_id),
    count(c2.item_id) 
from 
    cat_tb                  as a
    inner join item_tb      as b    on ( a.cat_id = b.cat_id )
    inner join cat_item_tb  as c1   on ( b.item_id = c1.item_id ) and ( c1.ss = 0 )
    inner join cat_item_tb  as c2   on ( b.item_id = c2.item_id ) and ( c2.ss = 1 )

由于内部连接,这将不起作用。如果 c1 的第一个连接返回 3 行,而 c2 的第二个连接返回 4 行,那么您最终会得到 count = 3*4

试试这个:

;with cte1 as (
    select
        b.item_id, 
        'c1_count' = count( c1.item_id ) 
    from
        item_tb                 as b
        left join cat_item_tb  as c1   on ( b.item_id = c1.item_id ) and ( c1.ss = 0 )        
    group by
        b.item_id
),
cte2 as (
    select 
        b.item_id,
        'c2_count' = count(c2.item_id) 
    from 
        item_tb                 as b        
        left join cat_item_tb  as c2   on ( b.item_id = c2.item_id ) and ( c2.ss = 1 )
    group by
        b.item_id
)
select
    a.item_id, a.c1_count, b.c2_count
from
    cte1            as a
    inner join cte2 as b on ( b.item_id = a.item_id )

出于性能原因,如果您确定 cat_item_tb 中有 行带有 item_id 和 所有这些将 ss 列设置为 0 或 1。

【讨论】:

    【解决方案2】:

    如果我对任务的理解正确,您可以使用 groub by 来获得所需的结果

    select count(cat_item_tb.item_id), cat_item_tb.ss
    from cat_tb 
    inner join item_tb on cat_tb.cat_id = item_tb.cat_id
    inner join cat_item_tb on item_tb.item_id = cat_item_tb.item_id 
    where t.ss = 0 or t.ss = 1
    group by cat_item_tb.ss
    

    查询将返回 2 行,第一列中有计数值。

    更多关于group by的信息在这里link

    【讨论】:

      【解决方案3】:

      在我看来,您需要计算不同的值,计算唯一值

      ... 
      count(DISTINCT cat_item_tb.item_id) 
      ...
      

      查询中的 2 个计数将相同。这仅仅是因为您在这些 item_id 上进行了 INNER JOIN。所以它们在定义上是相同的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-24
        • 2014-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-02
        相关资源
        最近更新 更多