简体   繁体   中英

How can I combine two columns that I get from a query into a third column in the same query?

I have an SQL query that gives me two columns with the price of some items. Is it possible within this same query to combine those two columns to get a total columns? Any ideas?

Current code:

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

Here is a picture of what I am trying to do:

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

Thanks!

Just as what Jorge said,

Add something like

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

You can use Common Table Expression (CTE's) as alternative to subqueries for a better performance, the query is clearer (easy to read an understand) and has much better structure.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM