代码之家  ›  专栏  ›  技术社区  ›  RRTW

Oracle统计我使用的数据

  •  1
  • RRTW  · 技术社区  · 8 年前

    假设我有一张这样的桌子

    ID, SN, USED
    
    002, 183000153206, 0
    002, 180000205206, 0
    002, 188000373206, 0
    002, 186000495206, 0
    002, 181000521206, 0
    
    001, 180000107106, 0
    001, 181000206106, 0
    001, 182000337106, 0
    001, 180000453106, 1
    001, 188000557106, 0
    001, 184000639106, 0
    

    我想计算每个ID使用的sn计数,如果我的SQL脚本是正确的,结果可能是:

    ID, USED_Count
    002, 0
    001, 1
    

    这是我到目前为止所做的,但它只显示了ID 001记录,没有ID 002。

    select   id, count(sn) as sums
    from     sn_table
    where    sn is not null
    and      used is not null
    group by id
    --having   sums >= 0
    

    我知道情况 使用不为空 似乎不太对,但我只是在这里储存了几个小时,我怎么能做到呢?

    2 回复  |  直到 8 年前
        1
  •  3
  •   Gordon Linoff    8 年前

    你可以用简单的 SUM :

    select   id, SUM(used) as sums
    from     sn_table
    group by id
    order by id desc;
    

    或条件聚合:

    SELECT id, COUNT(DISTINCT CASE WHEN used = 1 THEN sn END) AS USED_COUNT
    FROM sn_table
    GROUP BY id;
    

    DBFiddle Demo

        2
  •  0
  •   APC    8 年前

    不清楚你要实现的逻辑是什么。也许您只想计算每列的不同出现次数?

    select   id
             , count(distinct sn) as sn_cnt
             , count(distinct used) as used_cnt
    from     sn_table
    where    sn is not null
    and      used is not null
    group by id