SQL Server行计数在同一个表中多次返回内连接

时间:2018-05-19 11:57:14

标签: sql sql-server count

我有这段代码

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)

非常感谢

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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

您的查询中的2个计数将是相同的。这只是因为你在那些item_id上加入了INNER。因此,他们将通过捍卫来保持一致。

答案 2 :(得分:0)

我相信你想写一些类似的东西:

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 )

出于性能原因,如果您确定{{1}中有 行,则可以使用left join 替换ctes中的inner join使用item_id和所有cat_item_tb列设置为0或1。