我有一个T-SQL查询,它按国家计算销售总额:
SELECT
SUM(F_Sales_Month.Sales_Qty), D_Customer.Country
FROM
F_Sales_Month
INNER JOIN
D_Customer ON F_Sales_Month.CustomerKey = D_Customer.CustomerKey
GROUP BY
D_Customer.Country
结果:
如何获得百分比而非金额?
答案 0 :(得分:2)
这可能是效率最高的
exports.myFunc = functions.https.onRequest(async(request, response) => {
const snapshots = await admin.database().ref('/Employees').once('value')
let data_snap_arr = Object.keys(snapshots.val() || {}) .map(k => snapshots.val()[k]);
await Promise.all(data_snap_arr.map(handleSnapshot))
response.send("WOKAY!")
})
答案 1 :(得分:0)
我会使用窗口函数:
SELECT c.Country SUM(sm.Sales_Qty),
SUM(sm.Sales_Qty) * 1.0 / SUM(SUM(sm.Sales_Qty)) OVER () as country_ratio
FROM F_Sales_Month sm INNER JOIN
D_Customer c
ON sm.CustomerKey = c.CustomerKey
GROUP BY c.Country;
* 1.0
是因为某些数据库进行整数除法。如果你真的想要0到100之间的百分比,那么使用* 100.0
。
答案 2 :(得分:0)
这应该给出你的百分比
SELECT sum(F_Sales_Month.Sales_Qty),
sum(F_Sales_Month.Sales_Qty) / (SELECT sum(Sales_Qty)
FROM F_Sales_Month
INNER JOIN D_Customer ON
F_Sales_Month.CustomerKey = D_Customer.CustomerKey) * 100.0
as [PERCENT]
D_Customer.Country
FROM F_Sales_Month
INNER JOIN D_Customer ON F_Sales_Month.CustomerKey = D_Customer.CustomerKey
GROUP BY D_Customer.Country
使用基于AdventureWorks2017的示例SQL Fiddle ...