Adding a percent column to MS Access Query

微笑、不失礼 提交于 2019-12-04 19:34:07
HansUp

You can get all but the last row of your desired output with this query.

SELECT
    y.Product,
    y.Total,
    Format((y.Total/sub.SumOfTotal),'#.##%') AS Percentage
FROM
    YourTable AS y,
    (
        SELECT Sum(Total) AS SumOfTotal
        FROM YourTable
    ) AS sub;

Since that query does not include a JOIN or WHERE condition, it returns a cross join between the table and the single row of the subquery.

If you need the last row from your question example, you can UNION the query with another which returns the fabricated row you want. In this example, I used a custom Dual table which is designed to always contain one and only one row. But you could substitute another table or query which returns a single row.

SELECT
    y.Product,
    y.Total,
    Format((y.Total/sub.SumOfTotal),'#.##%') AS Percentage
FROM
    YourTable AS y,
    (
        SELECT Sum(Total) AS SumOfTotal
        FROM YourTable
    ) AS sub
UNION ALL
SELECT
    'Product',
    DSum('Total', 'YourTable'),
    '100%'
FROM Dual;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!