2013-04-29 61 views
1

我正在寫一個ColdFusion頁面來生成一個Excel表,如下所示:enter image description here如何壓縮多個select count查詢以提高代碼效率?

我想從數據庫中的一個表中生成多列信息。對於每一列,我都需要一個SELECT COUNT來獲得結果。喜歡這個;

Select count (yT) as pageOneView from tTable where userGUID=#Query.guid# AND id='00101' 

Select count (yT) as pageTwoView from tTable where userGUID=#Query.guid# AND id='00201' 

Select count (yT) as pageThreeView from tTable where userGUID=#Query.guid# AND id='00301' 

請注意,唯一更改的細節是計數名稱和id。 如何將這些組合成一個<cfquery>而不是每個都使用<cfquery>

+0

你想以表格形式或以行形式得到結果。 – 2013-04-29 09:12:31

回答

4

編輯迴應評論

如果你只是想顯示「布爾」值,那麼它的低效計算所有行。

select 
    case when exists 
     (select * from tTable 
      where guid = #Query.guid# 
       and yT is not null 
       and id = '00101') 
     then 'True' else 'False' end pageOneView, 
    case when exists 
     (select * from tTable 
      where guid = #Query.guid# 
       and yT is not null 
       and id = '00201') 
     then 'True' else 'False' end pageTwoView, 
    case when exists 
     (select * from tTable 
      where guid = #Query.guid# 
       and yT is not null 
       and id = '00301') 
     then 'True' else 'False' end pageThreeView 

這樣,

select 
     count(case id when '00101' then yT end) pageOneView, 
     count(case id when '00201' then yT end) pageTwoView, 
     count(case id when '00301' then yT end) pageThreeView 
    from 
     tTable 
    where 
     userGUID = #Query.guid#; 

注意Andomar's answer使用更少的代碼,並且可以通過你的SQL引擎更有效地處理,但是,doesen't相當與返回結果集你想要的模式。

+0

另外如果計數大於0,我怎樣才能顯示一個布爾值? – blarg 2013-04-29 09:24:50

+0

也剛剛意識到這個代碼並沒有考慮到yT列。 – blarg 2013-04-29 09:26:48

+1

+1編輯爲不計數'yT爲空'行 – Andomar 2013-04-29 09:31:32

1
select id 
,  count (itn) 
from tTable 
where userGUID = #Query.guid# 
     and id in ('00101', '00201', '00301') 
group by 
     id 
+0

但是我怎樣才能爲每個選擇應用一個名稱? – blarg 2013-04-29 09:19:54