在单个查询中以总和的百分比汇总表
Posted
技术标签:
【中文标题】在单个查询中以总和的百分比汇总表【英文标题】:Summarize tables with percent of sum in single query 【发布时间】:2017-03-20 23:38:40 【问题描述】:我有一个ACTIVE_TRANSPORTATION
表:
+--------+----------+--------+
| ATN_ID | TYPE | LENGTH |
+--------+----------+--------+
| 1 | SIDEWALK | 20.6 |
| 2 | SIDEWALK | 30.1 |
| 3 | TRAIL | 15.9 |
| 4 | TRAIL | 40.4 |
| 5 | SIDEWALK | 35.2 |
| 6 | TRAIL | 50.5 |
+--------+----------+--------+
它通过ATN_ID
与INSPECTION
表相关:
+---------+--------+------------------+
| INSP_ID | ATN_ID | LENGTH_INSPECTED |
+---------+--------+------------------+
| 101 | 2 | 15.2 |
| 102 | 3 | 5.4 |
| 103 | 5 | 15.9 |
| 104 | 6 | 20.1 |
+---------+--------+------------------+
我想把信息总结如下:
+----------+--------+-------------------+
| TYPE | LENGTH | PERCENT_INSPECTED |
+----------+--------+-------------------+
| SIDEWALK | 85.9 | 36% |
| TRAIL | 106.8 | 23% |
+----------+--------+-------------------+
如何在单个查询中做到这一点?
【问题讨论】:
【参考方案1】:这里是使用 ACCESS 2010 更新的答案。注意LENGTH
在 ACCESS 中是保留的,所以需要改成LENGTH_
SELECT
TYPE,
SUM(LENGTH) as LENGTH_,
SUM(IIF(ISNULL(LENGTH_INSPECTED),0, LENGTH_INSPECTED))/SUM(LENGTH) as PERCENT_INSPECTED
FROM
ACTIVE_TRANSPORTATION A
LEFT JOIN INSPECTION B
ON A.ATN_ID = B.ATN_ID
GROUP BY TYPE
这是我最初在 SQL SERVER 2014 中使用 T-SQL 的答案
SELECT SUM(LENGTH) as LENGTH,
SUM(ISNULL(LENGTH_INSPECTED,0))/SUM(LENGTH) as PERCENT_INSPECTED,
TYPE
FROM
ACTIVE_TRANSPORTATION A
LEFT JOIN INSPECTION B
ON A.ATN_ID = B.ATN_ID
GROUP BY TYPE
如果您需要将其转换为百分比、四舍五入等,请告诉我,但我猜这部分对您来说很容易。
【讨论】:
你还没有勇气尝试检查它是否在 Access 中运行?以上是关于在单个查询中以总和的百分比汇总表的主要内容,如果未能解决你的问题,请参考以下文章
Mongodb查询聚合和Groupby复杂过滤、求和、百分比查询