【问题标题】:Showing percentage for the group using MS SQL使用 MS SQL 显示组的百分比
【发布时间】:2021-10-14 10:18:24
【问题描述】:

我有以下疑问:

SELECT machine, start_date, sum(duration), 
st.status_code, st.status_text
FROM er_table er
LEFT JOIN status_table st on er.status_code=st.status_code
where machine in ('mach1','mach2','mach3')
group by machine, start_date, st.status_code, st.status_text
order by machine, start_date, status_text

它产生以下结果:

但是,我需要为特定日期的机器组添加一个百分比。例如。 9 月 15 日,mach1 空闲了 20 秒,因此,20/(20+800) 会给我 2% 的空闲时间。

这是我需要得到的结果:

我从类似的帖子中看到了一个类似的问题,我修改了我的代码如下,但它并没有完全给出我正在寻找的结果:

SELECT machine, start_date, sum(duration), 
SUM(duration) * 100.0 / SUM(SUM(duration)) OVER () AS Percentage,
st.status_code, st.status_text
FROM er_table er
LEFT JOIN status_table st on er.status_code=st.status_code
where machine in ('mach1','mach2','mach3')
group by machine, start_date, st.status_code, st.status_text
order by machine, start_date, status_text

非常感谢任何帮助。谢谢。

【问题讨论】:

    标签: mssql-jdbc


    【解决方案1】:
    SELECT machine, start_date, sum(duration), 
    
    SUM(duration) * 100.0 / SUM(duration) OVER(partition by machine, start_date) AS Percentage,
    
    st.status_code, st.status_text
    FROM er_table er
    LEFT JOIN status_table st on er.status_code=st.status_code
    where machine in ('mach1','mach2','mach3')
    group by machine, start_date, st.status_code, st.status_text
    order by machine, start_date, status_text
    

    这样做怎么样?

    我在 sum() over() 中使用了分区

    结果:

    machine start_date duration percentage status_code status_text
    mach1 2021-09-15 20 2.439024390243 1 IDLE
    mach1 2021-09-15 800 97.560975609756 1 RUNNING
    mach1 2021-09-16 40 4.255319148936 1 IDLE
    mach1 2021-09-16 900 95.744680851063 1 RUNNING
    mach2 2021-09-15 100 12.500000000000 1 IDLE
    mach2 2021-09-15 700 87.500000000000 1 RUNNING

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多