2015-04-03 32 views
0

我是新來的SQL,並且無法獲得結果來顯示錶1中存在但不是表2。我需要顯示每個ID有多少次表1已在表2中(包括0,如果沒有被使用的話),我可以得到的ID存在於表1中,顯示被使用,但不是ID不於表2獲得結果顯示在表1但不是表2中存在

I am getting: 
     ID Count 
      1 
      1 
      1 
      1 
      1 
      1 
      2 

but need: 
     ID Count 
      1 
      1 
      1 
      0 
      1 
      1 
      0 
      1 
      2 
存在的

我曾嘗試:

SELECT COUNT (PID) AS [ID Count] 
FROM SalesOrderProduct 
WHERE PID > = 0 
GROUP BY PID; 

(只此列,我不能得到0值顯示)

Table 1: PID, Description 
Table 2: PID, Status 

如何獲得顯示錶2中所有計數的ID的結果,包括使用UNION計數爲0時的計數?

謝謝大家

+0

哪個數據庫?你試過了什麼? – 2015-04-03 05:26:27

+0

恩,「哪個數據庫」 - 你是指我在用什麼程序? (對不起,這是非常新的) 我試過了: SELECT COUNT(SalesOrderProduct.PID)AS [ID Count] FROM SalesOrderProduct GROUP BY PID; (只是此列,我不能得到0值,以顯示) 表1:PID,描述 表2:PID,狀態 – 2015-04-03 05:34:15

+0

哪個數據庫中sqlserver'的'方式或'mysql' – 2015-04-03 05:42:53

回答

0

在這種情況下,你的IDS are not unique使用existscount加上union,如:

select distinct tbl.id, 0 cnt --for ids not exists in table2 
from table1 tbl 
where not exists (select t.id from table2 t where t.id=tbl.id) 
union 
select t1.id, count(t1.id) cnt ----for ids exists in table2 
from table1 t1 
where exists (select t2.id from table2 t2 where t1.id=t2.id) 
group by t1.id 
1

試試這個,你可以改變基於表結構的屬性名稱。

Select t1.id, count(t2.id) 

From t1 left join t2 
    on (t1.id = t2.id) 

Group By t1.id;