组合来自多个SQL查询的列

时间:2010-08-17 18:48:57

标签: sql-server-2005

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

- 获取在数据库中具有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

- 获取在数据库中具有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

18

计算EVP

18

是否可以将这些结果作为2个单独的列返回一行?

我尝试了一个联盟,但它创造了2行和1列

2 个答案:

答案 0 :(得分: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子句。这也意味着你只需要触摸一次表,所以如果它们相似,那么它应该远远超过许多结果集

答案 1 :(得分:0)

查看在select语句中创建函数或执行子查询。