2012-03-29 50 views
1

我有兩個表,分別叫做AB使用tsql從兩個表中減去計數

A包含請求詳細信息,如 request_id,company_idCustomer_id

表B含有反饋數據如feedback_idcompany_idstatus_indcustomer_idscore_total

我需要得到具有相應company_id與表AB的行數,其中status_ind1,並從表A的計數中減去。

+0

那些CheckATrade查詢繼續回來困擾着我 - PL :) – Phil 2012-03-29 12:11:57

+0

公頃公頃菲爾..它會.. – Joshua 2012-03-29 12:14:40

回答

2

我不知道你問什麼,但

declare @countA integer = (select count(*) from A) 

declare @countB integer = 
    (select count(*) from B where 
    exists(select * from A where A.company_id = B.company_id AND A.status_ind = 1) 

declare @difference integer = @countA - @countB 
+0

差不多。剛剛有一個想法 – Joshua 2012-03-29 13:21:01

0

你必須使用一個sql存儲過程或函數。

+0

呀你可以。但有點掙扎着查詢它自己。 – Joshua 2012-03-29 12:27:21

+0

您不需要存儲過程或函數。看到我的答案。 – mortb 2012-03-29 12:30:49

0

看過您的描述後,我不確定您想要做什麼。我把你的描述解釋爲:

SELECT id_company, countB - COALESCE(countA, 0) 
FROM 
(select id_company, count(*) as countB from TableB group by id_company) as t1 
left join (select id_company, count(*) as countA from TableA Where status_ind= 1 group by id_company) as t2 on t1.id_company = t2.id_company 

希望有幫助!

0

我也不能肯定。但我的理解是這樣的:

SELECT COUNT(*) FROM A WHERE company_id NOT IN (SELECT company_id FROM B WHERE status_ind = 1) 

我編輯它,我首先想到的是status_ind是表A沒有B中

0

好像你的問題可以改寫像這樣的:A數行時,與Bstatus_ind = 1行沒有匹配。

那麼,就用一個反連接,這樣,例如:

SELECT COUNT(*) 
FROM A 
    LEFT JOIN B ON A.company_id = B.company_id AND B.status_ind = 1 
WHERE B.company_id IS NULL