如何在变量中保存以下查询的值? SQL Server

时间:2016-08-08 21:43:36

标签: sql sql-server database performance

我需要实现两个变量来保存查询中的数据结果。

我有他跟随查询:

SELECT * FROM 
(SELECT location AS Location, COUNT(*) AS Trucks FROM Truck GROUP BY location) loc
OUTER APPLY
(
    SELECT 
        COUNT(*) AS TotalOfCampaings, 
        SUM(CASE WHEN cc.campaing_status = 'Complete' THEN 1 ELSE 0 END) AS CampaingsWithCompleteStatus, 
        SUM(CASE WHEN cc.campaing_status = 'InProcess' THEN 1 ELSE 0 END) AS CampaingsWithInProcessStatus
    FROM CampaingControl cc INNER JOIN Truck t ON cc.vin = t.vin 
    WHERE t.location = loc.location
) stat

此查询显示下一个表:

|地点|卡车| TotalOfCampaings | CampaingsWithCompleteStatus | CampaingsWithInProcessStatus

我需要在最后添加一个列,在新列中我需要获得具有完整状态的活动百分比,我尝试做这样的事情:

百分比=(CampaingsWithCompleteStatus / TotalOfCamapings)* 100

但我不知道如何保存查询的值来做到这一点。

1 个答案:

答案 0 :(得分:0)

这样的事情:

SELECT
    loc.Location,
    loc.Trunks,
    stat.TotalOfCampaings,
    stat.CampaingsWithCompleteStatus,
    stat.CampaingsWithInProcessStatus,
    (1.0 * stat.CampaingsWithCompleteStatus /stat.TotalOfCampaings) * 100 as [Percent]
FROM 
(SELECT location AS Location, COUNT(*) AS Trucks FROM Truck GROUP BY location) loc
OUTER APPLY
(
    SELECT 
        COUNT(*) AS TotalOfCampaings, 
        SUM(CASE WHEN cc.campaing_status = 'Complete' THEN 1 ELSE 0 END) AS CampaingsWithCompleteStatus, 
        SUM(CASE WHEN cc.campaing_status = 'InProcess' THEN 1 ELSE 0 END) AS CampaingsWithInProcessStatus
    FROM CampaingControl cc INNER JOIN Truck t ON cc.vin = t.vin 
    WHERE t.location = loc.location
) stat