2014-10-26 44 views
0

的次數我有一個這樣的表在我的分貝:查詢來獲取一個項目出現

id --- owner --- product ---- type 
0 --- john --- mustang ---- car 
1 --- tim --- a360 ---- plane 
2 --- john --- camry ---- car 
3 --- dan --- a380 ---- plane 
4 --- tim --- ninja ---- bike 
5 --- dan --- accord ---- car 

我試圖讓每種類型的所有者的數量。類似這樣的:

John 
Car = 2 
Plane = 0 
Bike = 0 
------------- 
Tim 
Car = 0 
Plane = 1 
Bike = 1 
------------- 
Dan 
Car = 1 
Plane = 1 
Bike = 0 
------------- 

我一直無法解決這個問題。

另一個問題是我的數據庫能夠接受新的類型。例如,某人可以添加一輛自行車作爲一種類型。

有沒有辦法做到這一點?

+0

我有點困惑,OP。被接受的答案不能給出你所期望的結果集。你究竟在尋找什麼? – AdamMc331 2014-10-26 21:44:40

回答

0

爲了解決這個問題,首先你要生成輸出行,然後拿到數:

select o.owner, p.product, count(t.owner) 
from (select distinct owner from table) o cross join 
    (select distinct product from table) p left join 
    table t 
    on t.owner = o.owner and t.product = p.product 
group by o.owner, p.product; 

如果您對業主和產品參考表,那麼你可以用這些代替select distinct子查詢。

編輯:

按類型分組基本上是相同的想法:

select o.owner, ty.type, count(t.owner) 
from (select distinct owner from table) o cross join 
    (select distinct type from table) ty left join 
    table t 
    on t.owner = o.owner and t.type = ty.type 
group by o.owner, ty.type; 
+0

這不會給OP找到的結果集。 – AdamMc331 2014-10-26 21:08:03

+0

@ McAdam331。 。 。首先,以什麼方式?其次,OP接受了答案。 – 2014-10-27 02:56:18

+0

OP要求他們按類型分組,而不是產品。我不能說OP爲什麼接受這個,因爲它與他們要求的不一致,所以我不知道OP在這裏真的想要什麼。 – AdamMc331 2014-10-27 02:57:51

1

我走近這是一個有點棘手的方式。

我開始創建一個結果集,使用笛卡爾積爲每個人和類型組合獲得一行。

SELECT m.owner, t.type 
FROM myTypes t, myTable m 
GROUP BY m.owner, t.type 

然後,我做了另一個結果集,抓住了所有者的所有者,類型和每種類型的數量。但是,這僅返回現有所有者類型組合的行。它不會返回說'約翰'和'飛機'的任何價值,因爲他沒有飛機產品。

SELECT m.owner, t.type, COUNT(*) as numOfType 
FROM myTypes t 
JOIN myTable m ON t.type = m.type 
GROUP BY t.type, m.owner; 

最後,我結合在一起使用的外這兩個表的聯接,所以我接收到的每一行從所有者型組合表。當然,有些行對於計數返回null,所以我必須使用IFNULL來將它們替換爲0.這與您的問題中的結果集相匹配。

SELECT w1.owner, w1.type, IFNULL(w2.numOfType, 0) AS numOfType 
FROM (SELECT m.owner, t.type 
    FROM myTypes t, myTable m 
    GROUP BY m.owner, t.type) w1 
LEFT JOIN (SELECT m.owner, t.type, COUNT(*) as numOfType 
    FROM myTypes t 
    JOIN myTable m ON t.type = m.type 
    GROUP BY t.type, m.owner) w2 
ON w1.owner = w2.owner AND w1.type = w2.type; 

這裏是SQL Fiddle