显示使用 MS SQL 组的百分比

Showing percentage for the group using MS SQL

我有以下查询:

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% 的闲置时间。

这是我需要得到的结果:

我从类似的 post 看到了类似的问题,我修改了我的代码如下,但它并没有给出我正在寻找的结果:

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

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

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