2010-08-17 57 views
0

我有多个SQL查询(准确的说是25),并希望将结果作为一行结果返回。例如...结合多个SQL查询的列

--get有一个EnvPrint记录在数据库

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有一个VerifyEnvPrint记录在数据库

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 

这个条形码产生

CountEP

计数EVP

是否有可能与这些结果2分单独的列返回一行?

我尝试了联盟,但它使2行一列

回答

1

是的。利用COUNT忽略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 

这可以工作,因为您有非常相似的WHERE子句。这也意味着你只触摸表一次,所以如果它们相似,应该在很多结果集上快得多

+0

也许那应该是THEN 1 ELSE 0并且SUM不计数否?不批评只是观察...也会使一个不错的PIVOT查询...并且是这比我的更好,因为它只接触一次表+1 – SQLMenace 2010-08-17 19:00:30

+0

非常感谢!作为一个SQL NOOB是艰难的,但你们让我的生活变得更好! – 2010-08-17 19:02:21

+0

@SQLMenace:带有1或0的SUM将使DISTINCT无效。 COUNT/NULL不是很明显,但处理DISTINCT。我通常使用SUM/1/0。几天前我回答了类似的问题http://stackoverflow.com/questions/3483506 – gbn 2010-08-17 19:02:43

0

研究建立功能或在你的SELECT语句执行子查询。