我有一個資料集如下:
date store employee products sales
20210101 a ben 5 laptop
20210101 a ben 10 monitor
20210201 b tim 15 laptop
20210301 b tim 10 tablet
20210301 a ann 30 monitor
我想要做的是計算員工在作業班次中每分鐘銷售多少產品的比率。每位員工每個作業日有 6 小時輪班制。例如:在 2021 年 1 月 1 日ben的比率為(5 10)/(6*60) = 0.04。
我想創建一個動態計算,因此如果我們選擇store a,它會包含所有員工及其班次的已售產品比率。例如:store a 總共有一個比例:(5 10 30) / (6*60*2) = 0.06
如果我們選擇筆記本電腦,它應該有一個比例: (5 10 30) / (6*60*2) = 0.06
這是我嘗試過的查詢:
(SUM('products') OVER (PARTITION BY 'date', 'store', 'employee', 'sales')) / (6*60)
但是,這種計算不是動態的,我想我遺漏了一些東西。如果有人能給我一個建議,我將不勝感激。
uj5u.com熱心網友回復:
一個簡單的 group by with rollup 應該可以解決這個問題。您將能夠查看不同粒度級別(例如商店、商店 員工或商店 員工 產品)的 sales_per_minute。
with dummy_data as (
select '20210101' as date_, 'a' as store, 'ben' as employee, 5 as products, 'laptop' as sales
union all
select '20210101', 'a', 'ben', 10, 'monitor'
union all
select '20210201', 'a', 'tm', 15, 'laptop'
union all
select '20210301', 'a', 'tim', 10, 'tablet'
union all
select '20210301', 'a', 'ann', 30, 'monitor'
)
select
date_,
store,
employee,
sales,
ROUND(SUM(products)/(6*60), 2) as sales_per_minute
from
dummy_data
group by
date_, store, employee, sales with rollup
order by
1
輸出:
| 日期_ | 店鋪 | 員工 | 銷售量 | 每分鐘銷售額 |
|---|---|---|---|---|
| 空值 | 空值 | 空值 | 空值 | 0.19 |
| 20210101 | 空值 | 空值 | 空值 | 0.04 |
| 20210101 | 一種 | 空值 | 空值 | 0.04 |
| 20210101 | 一種 | 本 | 空值 | 0.04 |
| 20210101 | 一種 | 本 | 筆記本電腦 | 0.01 |
| 20210101 | 一種 | 本 | 監視器 | 0.03 |
uj5u.com熱心網友回復:
所有你想要的是SUM(products) / 360。現在撰寫查詢,以便您獲得總體比率或每個員工的比率或每個銷售額的比率等。這些只是不同的組:
select sum(products) / 360 as per_minute from mytable;
select store, sum(products) / 360 as per_minute from mytable group by store;
select employee, sum(products) / 360 as per_minute from mytable group by employee;
select sales, sum(products) / 360 as per_minute from mytable group by sales;
您當然也可以添加一個WHERE子句來限制它,例如 in where date = '20210101'。(順便說一句,您真的將日期存盤為字串嗎?或者這是您的示例資料中的顯示內容?如果它應該是日期,請使用日期文字:where date = date '2021-01-01'。)
當然,您可以創建復合組,例如
select date, employee, sum(products) / 360 as per_minute
from mytable
group by date, employee
order by date, employee;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/357298.html
下一篇:查找具有指定差值的所有數字
