如何将从查询中获取的两列合并到同一查询中的第三列?

时间:2015-10-16 00:36:56

标签: sql sql-server sql-server-2012

我有一个SQL查询,它给了我两个列,其中包含一些项目的价格。是否可以在同一个查询中组合这两列以获得总列数?有任何想法吗?

当前代码:

Select A.Company_Name,

(Select COUNT(v_rpt_Configuration.Config_Name)
From v_rpt_Configuration
Where v_rpt_Configuration.Company_RecID=A.Company_RecID and v_rpt_Configuration.Config_Type = 'Managed Workstation' and v_rpt_Configuration.ConfigStatus = 'Active') AS Workstations,

(Select COUNT(v_rpt_Configuration.Config_Name)
From v_rpt_Configuration
Where v_rpt_Configuration.Company_RecID=A.Company_RecID and v_rpt_Configuration.Config_Type LIKE '%Vendor%' and v_rpt_Configuration.ConfigStatus = 'Active') AS Vendors,

(Select '$' + CONVERT(varchar(12),(IV_Item.List_Price * Count(v_rpt_Configuration.Config_Name)),1)
From IV_Item, v_rpt_Configuration 
Where v_rpt_Configuration.Company_RecID=A.Company_RecID and v_rpt_Configuration.Config_Type = 'Managed Workstation' and v_rpt_Configuration.ConfigStatus = 'Active' and IV_Item.Description = 'RMM Managed Workstation' 
Group by IV_Item.List_Price) AS 'Workstation Costs',

(Select '$' + CONVERT(varchar(12),(IV_Item.List_Price * Count(v_rpt_Configuration.Config_Name)),1) 
From IV_Item, v_rpt_Configuration 
Where v_rpt_Configuration.Company_RecID=A.Company_RecID and v_rpt_Configuration.Config_Type Like '%Vendor%' and v_rpt_Configuration.ConfigStatus = 'Active' and IV_Item.Description = 'Managed Vendor' 
Group by IV_Item.List_Price)AS 'Vendor Costs'

From AGR_Header
join Company as A on AGR_Header.Company_RecID=A.Company_RecID
join Company_Type on A.Company_Type_RecID=Company_Type.Company_Type_RecID
where Company_Type.Description LIKE '%Client%' and AGR_Date_Cancel is null and AGR_Type_RecID=30
Order by A.Company_Name

这是我想要做的事情的图片:

[http://imgur.com/A4aUljv][1]

谢谢!

2 个答案:

答案 0 :(得分:0)

正如乔治所说,

添加类似

的内容
SELECT src.*, ([WorkStation Costs] + [Vendor Costs]) AS 'Total Costs'
FROM ( 
    your query here 
) AS src

答案 1 :(得分:0)

您可以使用公用表表达式(CTE' s)作为子查询的替代方案以获得更好的性能,查询更清晰(易于理解)并且具有更好的结构。

WITH <nameyourCTE> AS
(
<inner query>
)
<outer query>