SQL Server:使用新记录作为输出的百分比计算

时间:2018-10-28 05:09:30

标签: sql sql-server

我将下表作为SQL查询的输出

ID  Car Type    Units Sold
---------------------------
1   Sedan       250
2   SUV         125
3   Total       375

我想要一个SQL查询/过程在下面的输出中产生

ID  Car Type    Units Sold
--------------------------
1   Sedan       250
2   SUV         125
3   Total       375
4   Sedan_Pct   66.67 (250/375)
5   SUV_Pct     33.33  (125/375)

请注意,Car Type将来会增加,我希望将每种车型的百分比作为'_Pct'附加到当前表中。

5 个答案:

答案 0 :(得分:2)

通常,我们可能希望将百分比视为单独的,而不是单独的行。话虽如此,我们可以使用SQL Server中的分组集生成所需的输出:

WITH cte AS (
    SELECT ID, CarType, SUM (UnitsSold) AS UnitsSold
    FROM yourTable
    GROUP BY 
        GROUPING SETS((ID, CarType), (CarType), ())
)

SELECT
    ID,
    COALECSE(CarType, 'Total') AS CarType,
    CASE WHEN ID IS NOT NULL OR CarType IS NULL
         THEN UnitsSold
         ELSE 100.0 * UnitsSold /
             SUM(CASE WHEN ID IS NOT NULL THEN UnitsSold END) OVER () END AS PctUnitsSold
FROM cte
ORDER BY
    ID DESC,
    CASE WHEN CarType IS NULL THEN 0 ELSE 0 END,
    CarType;

enter image description here

Demo

答案 1 :(得分:0)

查询mysql服务器 在视图或存储过程中使用并集-

declare @totalunitsold numeric(15,0);
set @totalunitsold =  (select unitsold from car where cartype='total')

select cartype,unitsold from car

union all

select cartype + '_pct', (unitsold/@totalunitsold) as pct from car

答案 2 :(得分:0)

一个更简单的解决方案将使用Union

SELECT CarType, UnitSold FROM Car
UNION
SELECT 'Total' CarType, SUM(UnitSold) UnitSold FROM Car
UNION
SELECT CarType + '_Pct' AS CarType, UnitSold / (SELECT SUM(UnitSold) FROM Car) * 100 AS UnitSold FROM Car

从长远来看可能并不理想

答案 3 :(得分:0)

这可能对您有帮助

SELECT CarType+'_Pct', UnitSold/TotalSale*100 
FROM Car  cross join (select sum(UnitSold) TotalSale from Car) X

您可以将其与表格合并

答案 4 :(得分:0)

不要这样做!只需添加其他列,而不添加新行:

select t.*,
       t.units_sold * 100.0 / sum(case when t.car_type = 'Total' then units_sold end) over () as ratio
from (<your query here>) t;

想要不同的列的一个根本原因是因为ratiounits_sold的类型不同。列中的所有内容(甚至是结果集中的内容)都应具有相似的属性。