【问题标题】:oracle select two count values in one roworacle在一行中选择两个计数值
【发布时间】:2021-12-17 09:15:33
【问题描述】:

我需要有关 oracle 中此选择的帮助。我有两列的表:(表>日期,值)例如:

1.1.2017, 16
1.1.2017, 16
1.1.2017, 16
1.1.2017, 17
1.2.2017, 16
1.2.2017, 16
1.2.2017, 17
1.2.2017, 17
1.3.2017, 16

结果必须是:

1.1.2017 as date, 3 as count of 16, 1 as count of 17
1.2.2017, 2, 2
1.3.2017, 1, 0

当前 SQL:

select date, count(value) from table group by date, value

但是,这不会返回具有两个值计数的一行的相同日期。

【问题讨论】:

    标签: oracle


    【解决方案1】:

    你需要条件计数,像这样:

    with
         your_table ( dt, value ) as (
           select to_date('1.1.2017', 'mm.dd.yyyy'), 16 from dual union all
           select to_date('1.1.2017', 'mm.dd.yyyy'), 16 from dual union all 
           select to_date('1.1.2017', 'mm.dd.yyyy'), 16 from dual union all
           select to_date('1.1.2017', 'mm.dd.yyyy'), 17 from dual union all
           select to_date('1.2.2017', 'mm.dd.yyyy'), 16 from dual union all
           select to_date('1.2.2017', 'mm.dd.yyyy'), 16 from dual union all
           select to_date('1.2.2017', 'mm.dd.yyyy'), 17 from dual union all
           select to_date('1.2.2017', 'mm.dd.yyyy'), 17 from dual union all
           select to_date('1.3.2017', 'mm.dd.yyyy'), 16 from dual
         )
    --  end of test data; solution (SQL query) begins below this line
    select   dt, count(case value when 16 then 'x' end) as ct_16,
                 count(case value when 17 then 'x' end) as ct_17
    from     your_table
    group by dt;
    
    DT          CT_16  CT_17
    ----------  -----  -----
    01/01/2017      3      1
    01/02/2017      2      2
    01/03/2017      1      0
    

    【讨论】:

      【解决方案2】:

      按日期、值从表组中选择日期、值、计数(值);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-07
        • 1970-01-01
        • 1970-01-01
        • 2023-02-02
        • 1970-01-01
        • 1970-01-01
        • 2020-11-27
        • 1970-01-01
        相关资源
        最近更新 更多