2011-03-25 43 views
0

我需要從兩個表中選擇計數,這兩個表共享一個公共列,即clientId,並將總數除以clientIds,給定日期和dateadded列在這兩個表中都是日期時間格式。sql server - 從報表的兩個表中獲取計數和列值

例如,測試結果將顯示:

ClientId  Total1 Total2 
aaaa   1  2 
bbbbb   43  45 
ccccc   123 355 

等爲2011-03-25

我目前擁有的是

select 
    (select clientid,count(*) as total1 from TFeed where dateadded = getdate() 
    group by clientId), 
    (select clientId, count(*) as total2 from WFeed where dateadded = getdate() 
    group by clientid) 

這當然是錯誤的。 錯誤:子查詢未與EXISTS一起引入時,只能在選擇列表中指定一個表達式。此外,爲了考慮,這些表格非常大 - 超過300萬條記錄並不斷增長。任何幫助表示讚賞

編輯:

了時間 - 如果dateadded = '2011-03-25 12時零零分34秒0011',我哪有時間比較 GET dateadded = @getdate()和選擇今天的所有記錄。

雖然我的查詢仍在運行 - 關閉主題問題...因爲這是一個報告查詢,我想定期運行它來更新總數,以便當客戶端打開網頁或點擊報告時,它將提供總計而無需運行查詢並從數據庫中選擇最後的總計。那麼我需要有一個不同的查詢或每隔一小時左右運行一次。

回答

1

你很近。在進行彙總之前,您希望將兩個表格連接在一起

select 
    clientid, 
    sum(case when t.clientid is not null then 1 else 0 end) as total1 
    sum(case when w.clientid is not null then 1 else 0 end) as total1 
    from TFeed t FULL OUTER JOIN WFeed w 
    where w.dateadded = getdate() or t.dateadded = getdate() 

這可能不完全符合您的要求,但這是一般想法。這也處理了特定日期的某個表中沒有數據的情況。

+0

感謝執行它但它仍然在運行 - 採取這麼長的時間......差不多一個小時......就像我說的那樣,在這兩個表中大約有4百萬條記錄 – vbNewbie 2011-03-25 17:34:44

+0

你有沒有關於clientid的指示? – dfb 2011-03-25 17:39:51

+0

對不起沒有客戶IdI – vbNewbie 2011-03-25 17:46:58

1
select tf.clientid, 
     SUM(case when tf.dateadded = getdate() then 1 else 0 end) as Total1, 
     SUM(case when wf.dateadded = getdate() then 1 else 0 end) as Total2 
from tfeed tf full outer join wfeed wf on tf.clientid = wf.clientid 
group by tf.clientid 
+1

內部連接將消除不在兩個表中的記錄。另外,您構建查詢的方式將迭代所有評估case語句的記錄,並進行總和並忽略不落入日期條件的記錄。 – DidierDotNet 2011-03-25 16:40:13

+0

@DidierDotNet - 是的,你是對的。編輯。 – 2011-03-25 16:41:53

+0

謝謝,但內部連接不會正常工作 – vbNewbie 2011-03-25 17:32:58

0

嘗試一下這樣的事情。

select clientid, sum(total1) as total1, sum(total2) as total2 
from 
(select clientid,count(*) as total1, 0 as total2 
from TFeed 
where dateadded = @someDate 
group by clientId 
UNION 
select clientId, 0 as total1, count(*) as total2 
from WFeed 
where dateadded = @someDate 
group by clientid) 
group by clientid 
0

使用交叉應用真的很有幫助,並且顯着加快速度。我對你的關聯並不積極,你的2個提要中的客戶端ID是否有一對一的關係,但這是你想要針對這麼多記錄優化查詢的方向。

而且,這裏是另一個討論的鏈接與交叉的主題的更多信息,適用,如果這個確切的查詢是不適合你的工作可能會有所幫助:

When should I use Cross Apply over Inner Join?

with x as (
    select clientID as clientID, COUNT(*) as total1 
    from TFeed where dateadded = GETDATE() 
    group by clientID 
    ) 
    select x.clientID,x.total1,y.total2 from x 
    cross apply 
    (
     select clientID as clientID, COUNT(*) as total2 
     from WFeed where dateadded = GETDATE() 
     group by clientID 
    ) y 
相關問題