2015-03-31 25 views
0

連接表組我有QUERY_1如何通過計數

select id, 
     count(case when no01 ='B' then 1 END) + 
     count(case when no02='B' then 1 END) + 
     count(case when no03='B' then 1 END) as Count_All 

From tabel_a 
where date ='20150201' 
group by id 

enter image description here


,也是我有query_2

select id, COUNT (*) from tabel_b 
where ids <> 'T' and idt ='C' 
group by id 

我如何加入query_1query_2 via id

+0

謝謝基督教Goolhardt – SimanisJKT48 2015-03-31 05:01:05

回答

2

你可以嘗試使用子選擇。像

SELECT * 
FROM (
      select id, 
        count(case when no01 ='B' then 1 END) + count(case when no02='B' then 1 END) + count(case when no03='B' then 1 END) as Count_All 
      From tabel_a 
      where date ='20150201' 
      group by id 
     ) a INNER JOIN 
     (
      select id,  
        COUNT (*) cnt 
      from tabel_b 
      where ids <> 'T' 
      and  idt ='C' 
      group by id 
     ) b ON a.ID = b.ID 

爲您指定的SQL Server看到的東西,你也可以使用一個Common Table Expression的。

喜歡的東西

;WITH a AS (
    select id, 
      count(case when no01 ='B' then 1 END) + count(case when no02='B' then 1 END) + count(case when no03='B' then 1 END) as Count_All 
    From tabel_a 
    where date ='20150201' 
    group by id 
) 
, b as (
    select id,  
      COUNT (*) cnt 
    from tabel_b 
    where ids <> 'T' 
    and  idt ='C' 
    group by id 
) 
SELECT * 
FROm a INNER JOIN 
     b ON a.ID = b.ID 
+0

感謝的阿德里安旁觀者......你非常有幫助 – SimanisJKT48 2015-03-31 04:35:07

+0

枝阿德里安旁觀者..我怎麼更迭在你的答案... 結果這樣的.. ID | countall | id | cnt 1 | 2 | 1 | 6 我怎麼會這樣? id | countall | cnt | 1 | 2 | 6 | – SimanisJKT48 2015-03-31 05:01:24

+0

哦謝謝...我可以做到這一點... select * from = select a.id,countall,cnt .. hehe ..非常感謝adriaan ... – SimanisJKT48 2015-03-31 05:06:22