Please start any new threads on our new site at http://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Use Alias for Calculated Columns
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

rnelsch
Starting Member

USA
31 Posts

Posted - 01/29/2013 :  09:43:51  Show Profile  Reply with Quote
Is it possible to use an alias to create a new calculated column. For example, I have the following query:

SELECT COUNT(DISTINCT JOB.JobID) AS JobsRun,
COUNT (DISTINCT CASE WHEN Job.SaleIsSold = 'True' THEN JOB.JobId END) as JobsSold
FROM JOB
WHERE JOB.PrimaryEmp = '294'
AND JOB.SchedDate between '12/27/2012' and '1/23/2013'

And I'd like to ad a calculated column to get the difference between JobsRun and Jobs Sold so I tried the following but it doesn't work:

SELECT COUNT(DISTINCT JOB.JobID) AS JobsRun,
COUNT (DISTINCT CASE WHEN Job.SaleIsSold = 'True' THEN JOB.JobId END) as JobsSold,
JobsRun - JobsSold as NotSold
FROM JOB
WHERE JOB.PrimaryEmp = '294'
AND JOB.SchedDate between '12/27/2012' and '1/23/2013'

Ryan A Nelsch

rnelsch
Starting Member

USA
31 Posts

Posted - 01/29/2013 :  09:46:27  Show Profile  Reply with Quote
Nevermind I fixed this with the following in case anyone was interested:

SELECT COUNT(DISTINCT JOB.JobID) AS JobsRun,
COUNT (DISTINCT CASE WHEN Job.SaleIsSold = 'True' THEN JOB.JobId END) as JobsSold,
COUNT (DISTINCT CASE WHEN Job.SaleIsSold = 'False' THEN JOB.JobId END) as NotSold
FROM JOB
WHERE JOB.PrimaryEmp = '294'
AND JOB.SchedDate between '12/27/2012' and '1/23/2013'

Ryan A Nelsch
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52326 Posts

Posted - 01/29/2013 :  09:46:54  Show Profile  Reply with Quote
you cant use aliases created in same level like this. it should be

SELECT *,
JobsRun - JobsSold as NotSold
FROM
(
SELECT COUNT(DISTINCT JOB.JobID) AS JobsRun,
COUNT (DISTINCT CASE WHEN Job.SaleIsSold = 'True' THEN JOB.JobId END) as JobsSold
FROM JOB
WHERE JOB.PrimaryEmp = '294'
AND JOB.SchedDate between '12/27/2012' and '1/23/2013'
)t



------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.88 seconds. Powered By: Snitz Forums 2000