2010-08-17 68 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語句執行子查詢。