【问题标题】:SQL Queries Count with a condition带有条件的 SQL 查询计数
【发布时间】:2022-07-07 23:46:11
【问题描述】:

我是第一次使用 SQL 查询并学习它。 我有一张这样的桌子:

yearName productcompanyID
2001 ID 1
2001 ID 1
2001 ID 2
2001 ID 1
2001 ID 1
2002 ID 1
2002 ID 1
2002 ID 2
2002 ID 2
2003 ID 2

我想计算 productcompanyID 出现的次数,但一年只计算一次。 (对不起,我的英语不是我的语言,我可能不太清楚)

我的意思是,目前我已经写了这个 SQL:

  SELECT DISTINCT(productcompanyid),
    COUNT(productcompanyid)
  FROM mydatabase
  GROUP BY productcompanyid

它给我的结果是 ID 1: 6 和 ID 2: 4。

我想要的是 ID 1:2(因为它在 2001 年和 2002 年至少出现一次)和 ID 2:3(因为它在 2001 年、2002 年和 2003 年至少出现一次)

感谢您的帮助。

【问题讨论】:

  • 听起来您想计算每个 productcompanyid 出现的不同 的数量,但您要求计算 productcompanyid,不是不同年份的计数。

标签: sql sql-server


【解决方案1】:

您实际上需要将 count 和 distinct 结合起来,如下所示:

select productcompanyID, count(distinct yearName) as distinctYears
from mydatabase
group by productcompanyID

【讨论】:

    【解决方案2】:

    最简单的查询和一些额外的性能是使用 2 级聚合,如下所示:

    --create temp table named #table1 and add row1
    
    select 2001 yearName,   'ID 1' productcompanyID into #table1
    
    
    --add remaining rows to #table1
    
    insert into #table1
    
    select 2001,    'ID 1' union all
    
    select 2001,    'ID 2' union all
    
    select 2001,    'ID 1' union all
    
    select 2001,    'ID 1' union all
    
    select 2002,    'ID 1' union all
    
    select 2002,    'ID 1' union all
    
    select 2002,    'ID 2' union all
    
    select 2002,    'ID 2' union all
    
    select 2003,    'ID 2' 
    
    
    --/query to count how many times a productcompanyID appear each a year*/
    
    
    select productcompanyID, count(1) cnt
    
    from (
    
        select yearName, productcompanyID
    
        from #table1 
    
        group by yearName, productcompanyID
    
    )a
    
    group by productcompanyID
    

    它应该给出你在问题上提出的结果。

    【讨论】:

      猜你喜欢
      • 2014-04-09
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 2021-10-23
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多