views:

19

answers:

2

I have more than one sql query(25 to be exact) and want to return the results as one row of results. for example...

--Get the Barcodes that have a EnvPrint Record in the Database

select  count(distinct jtbarcode) as CountEP 
from jobtracker with(nolock)
where jtprocess = 'EnvPrint' and jtbarcode in(Select lookupcode from data with(nolock) where clientid = 123 and batchid = 12345 and jobid = 1 and subjobid = 1 and entrytype<>'c' and entrytype<>'m')
GROUP BY jtBatchid

--Get the Barcodes that have a VerifyEnvPrint Record in the Database

select  count(distinct jtbarcode) as CountEVP
from jobtracker with(nolock) 
where jtprocess = 'Verify-EnvPrint' and jtbarcode in(Select lookupcode from data with(nolock) where clientid = 123 and batchid = 12345 and jobid = 1 and subjobid = 1 and entrytype<>'c' and entrytype<>'m')  
GROUP BY jtBatchid

this produces

CountEP

18

Count EVP

18

Is it possible to return one row with those results as 2 separate columns?

I tried a Union but it made 2 rows and one column

A: 

Look into creating functions or performing sub queries in your select statement.

Jay
+1  A: 

yes. Leverage the fact that COUNT ignores NULL

select
     count(distinct CASE WHEN jtprocess = 'Verify-EnvPrint' THEN jtbarcode ELSE NULL END) as CountEVP ,
     count(distinct CASE WHEN jtprocess = 'EnvPrint' THEN jtbarcode ELSE NULL END) as CountEP 
from jobtracker with(nolock)

where jtprocess IN ('Verify-EnvPrint', 'EnvPrint')

    and jtbarcode in(Select lookupcode from data with(nolock) where clientid = 123 and batchid = 12345 and jobid = 1 and subjobid = 1 and entrytype<>'c' and entrytype<>'m')
GROUP BY jtBatchid

This works because you have very similar WHERE clauses. It also means you only touch the table once too so should be far quicker over many result sets if they are similar

gbn
perhaps that should be THEN 1 ELSE 0 and Also SUM not count no? Not criticizing just observing...would also make for a nice PIVOT query..and yes this is better than mine since it touches the table only once +1
SQLMenace
Thanks MUCH! Being a SQL NOOB is tough, but you guys make my life way better!
Confused SQL User
@SQLMenace: SUM with 1 or 0 will invalidate DISTINCT though. The COUNT/NULL is not as obvious but deals with DISTINCT. I'd normally use SUM/1/0. I answered similar a few days ago http://stackoverflow.com/questions/3483506
gbn
Duh...no wonder if works with count...time to grab some caffeine :-(
SQLMenace