2014-10-11 47 views
0

,我有以下表中的數據:MySQL的計數cccurrence並加入回同桌

ID DrawDate DrawNumber 
1 01/01/2014 1234 
2 01/01/2014 1235 
3 01/01/2014 1236 
4 02/01/2014 1237 
5 02/01/2014 1234 
6 02/01/2014 1238 
7 03/01/2014 1234 
8 03/01/2014 1235 
9 03/01/2014 1239 

我想MySQL的計數DrawNumber的發生,並填充回的結果是顯示如下:

ID DrawDate DrawNumber Occuurence 
1 01/01/2014 1234  3 
2 01/01/2014 1235  2 
3 01/01/2014 1236  1 
4 02/01/2014 1237  1 
5 02/01/2014 1234  3 
6 02/01/2014 1238  1 
7 03/01/2014 1234  3 
8 03/01/2014 1235  2 
9 03/01/2014 1239  1 

我設法擁有以下MYSQL代碼,但它似乎將現有數據庫的總記錄數加倍。

SELECT 
DISTINCT table.ID, table.DrawDATE,table.DrawNumber. 
(SELECT 
COUNT(table.ID) 
FROM table 
WHERE table1.DrawNumber = table.DrawNumber 
) AS Occuurence 

FROM table 
INNER JOIN table AS table1 ON table.DrawNumber = table1.DrawNumber 
ORDER BY table.DrawDATE DESC 

任何人都可以建議更好的MySQL查詢?

在此先感謝。

CK

回答

0

嘗試如下:

SELECT 
DISTINCT a.ID, a.DrawDATE,a.DrawNumber,count(a.DrawNumber) as occurance 
(select * FROM table 
ORDER BY table.DrawDATE DESC)a group by a.DrawNumber 

如果你不想要,如果你想保持相同數量的記錄在輸出相同的表,那麼你可以在下面嘗試使用組查詢:

SELECT 
DISTINCT table.ID, table.DrawDATE,table.DrawNumber. 
(SELECT 
COUNT(table.ID) 
FROM table 
WHERE table1.DrawNumber = table.DrawNumber 
) AS Occuurence 

FROM table 
ORDER BY table.DrawDATE DESC 
0

感謝Ronak Shah回答。

我使用另一種方法,其中我創建一個視圖來獲得count的結果,然後返回表。它工作正常。