在单个查询中汇总具有和百分比的表

时间:2017-03-20 23:38:40

标签: sql ms-access group-by ms-access-2010 aggregate

我有一个O(N)表:

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 | +--------+----------+--------+

INSPECTION表相关
ATN_ID

我想总结一下这样的信息:

+---------+--------+------------------+
| INSP_ID | ATN_ID | LENGTH_INSPECTED |
+---------+--------+------------------+
|     101 |      2 |             15.2 |
|     102 |      3 |              5.4 |
|     103 |      5 |             15.9 |
|     104 |      6 |             20.1 |
+---------+--------+------------------+

如何在单个查询中执行此操作?

1 个答案:

答案 0 :(得分:2)

以下是使用ACCESS 2010的更新答案。请注意,<script src="js/drawingboard.min.js"></script> <script data-example="1"> var defaultBoard = new DrawingBoard.Board("default-board", { background: "#ffff", droppable: true, webStorage: false, enlargeYourContainer: true, addToBoard: true, stretchImg: false }); defaultBoard.addControl("Download"); $(".drawing-form").on("submit", function(e) { var img = defaultBoard.getImg(); var imgInput = (defaultBoard.blankCanvas == img) ? "" : img; $(this).find("input[name=image]").val( imgInput ); defaultBoard.clearWebStorage(); }); $(function() { $("#file-input").change(function(e) { var file = e.target.files[0], imageType = /image.*/; if (!file.type.match(imageType)) return; var reader = new FileReader(); reader.onload = fileOnload; reader.readAsDataURL(file); }); function fileOnload(e) { var canvas = $("#default-board")[0]; var context = canvas.getContext("2d"); var background = new Image; background.src = canvas.style.background.replace(/url\(/|\)/gi,"").trim(); background.onload = function(){ var $img = $("<img>", { src: e.target.result }); $img.load(function() { context.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height); context.drawImage(this, 0, 0); }); } } }); 在ACCESS中保留,因此需要更改为LENGTH

LENGTH_

以下是我最初使用SQL SERVER 2014中使用T-SQL的答案

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

如果您需要将其转换为百分比,四舍五入等,请告诉我,但我猜这部分很容易。