select date_format(CREATETIME,'YYYY') as year, count(id) as xmsl,--项目数量 sum(ZBPRICE) as totalInvestment, --总投资 TENDER as fbfs, CASE WHEN (TENDER = 'GK')THEN '公开招标' WHEN (TENDER = 'YQ' )THEN '邀请招标' WHEN (TENDER = 'QTZB' )THEN '简易(直接发包?)' ELSE '空' end "发包方式" from MHXXM.OA_Form_FinalZBUnit --where CREATETIME like '2021%' GROUP BY date_format(CREATETIME,'YYYY'),TENDER order by CREATETIME desc; 如何查询sum(zbprice)在分组后GROUP BY date_format(CREATETIME,'YYYY'),TENDER 的sum(*)的占比
理解问题select date_format(CREATETIME,'YYYY') as year, count(id) as xmsl,--项目数量 sum(ZBPRICE) as totalInvestment, --总投资 TENDER as fbfs, CASE WHEN (TENDER = 'GK')THEN '公开招标' WHEN (TENDER = 'YQ' )THEN '邀请招标' WHEN (TENDER = 'QTZB' )THEN '简易(直接发包?)' ELSE '空' end "发包方式" from MHXXM.OA_Form_FinalZBUnit --where CREATETIME like '2021%' GROUP BY date_format(CREATETIME,'YYYY'),TENDER order by CREATETIME desc; 如何查询sum(zbprice)在分组后GROUP BY date_format(CREATETIME,'YYYY'),TENDER 的sum(*)的占比
已完成理解「select date_format(CREATETIME,'YYYY') as year, count(id) as xmsl,--项目数量 sum(ZBPRICE) as totalInvestment, --总投资 TENDER as fbfs, CASE WHEN (TENDER = 'GK')THEN '公开招标' WHEN (TENDER = 'YQ' )THEN '邀请招标' WHEN (TENDER = 'QTZB' )THEN '简易(直接发包?)' ELSE '空' end "发包方式" from MHXXM.OA_Form_FinalZBUnit --where CREATETIME like '2021%' GROUP BY date_format(CREATETIME,'YYYY'),TENDER order by CREATETIME desc; 如何查询sum(zbprice)在分组后GROUP BY date_format(CREATETIME,'YYYY'),TENDER 的sum(*)的占比」
展开阅读网页
在SQL查询中计算sum(zbprice)
在分组后GROUP BY date_format(CREATETIME,'YYYY'), TENDER
的占比,可以通过嵌套查询和窗口函数来实现。具体来说,可以使用SUM()
函数和OVER()
子句来计算总和,然后在SELECT
语句中计算占比。以下是详细的步骤和示例代码。
核心答案
要计算sum(zbprice)
在分组后的占比,可以使用嵌套查询和窗口函数。首先,计算每个分组的总和,然后在外层查询中计算该分组占总和的百分比。12
📊 计算分组后的总和
首先,我们需要计算每个分组的总和。使用GROUP BY
子句对date_format(CREATETIME, 'YYYY')
和TENDER
进行分组,并计算每个分组的sum(zbprice)
。
SELECT
date_format(CREATETIME, 'YYYY') AS year,
TENDER AS fbfs,
SUM(ZBPRICE) AS totalInvestment
FROM
MHXXM.OA_Form_FinalZBUnit
GROUP BY
date_format(CREATETIME, 'YYYY'), TENDER
ORDER BY
year DESC;
📈 计算占比
接下来,使用窗口函数SUM(SUM(ZBPRICE)) OVER()
来计算总和,并在SELECT
语句中计算占比。
SELECT
year,
fbfs,
totalInvestment,
ROUND((totalInvestment * 100.0 / totalSum), 2) AS percentage
FROM
(
SELECT
date_format(CREATETIME, 'YYYY') AS year,
TENDER AS fbfs,
SUM(ZBPRICE) AS totalInvestment,
SUM(SUM(ZBPRICE)) OVER() AS totalSum
FROM
MHXXM.OA_Form_FinalZBUnit
GROUP BY
date_format(CREATETIME, 'YYYY'), TENDER
) AS subquery
ORDER BY
year DESC;
🔍 详细解释
- 嵌套查询:首先在内部查询中计算每个分组的
totalInvestment
和总和totalSum
。 - 窗口函数:使用
SUM(SUM(ZBPRICE)) OVER()
计算总和,确保每个分组的totalSum
是相同的。 - 计算占比:在外层查询中,使用
ROUND((totalInvestment * 100.0 / totalSum), 2)
计算每个分组的占比,并保留两位小数。
🛠️ 解决方案和操作步骤
- 编写嵌套查询:首先编写内部查询,计算每个分组的
totalInvestment
和总和totalSum
。 - 使用窗口函数:在内部查询中使用
SUM(SUM(ZBPRICE)) OVER()
计算总和。 - 计算占比:在外层查询中,使用
ROUND((totalInvestment * 100.0 / totalSum), 2)
计算每个分组的占比。 - 排序结果:使用
ORDER BY year DESC
对结果进行排序。