2012-03-04 177 views
0

下面是我的工作表:各種配套是隻有唯一一起MySQL查詢 - 分組通過聯合IDS

CREATE TABLE `index` (
`wid` int(7) unsigned NOT NULL, 
`pid` int(7) unsigned NOT NULL, 
`value` tinyint(3) unsigned NOT NULL DEFAULT '0', 
UNIQUE KEY `wid` (`wid`,`pid`), 
KEY `pid` (`pid`), 
KEY `value` (`value`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 

我的「PID」整數「婦女參與發展」。

舉例來說,我有:

pid - wid - value 
1 - 5 - 7 
1 - 6 - 5 
1 - 7 - 9 
2 - 5 - 2 
2 - 8 - 4 
3 - 8 - 8 
3 - 7 - 12 
4 - 5 - 5 
.. - .. - .. 

現在讓我們假設我想要得到PID其中WID相匹配值的總和最高的5和7的順序。

因此,PID 1匹配2個WID(5,7),其總和值爲16(7 + 9)。 和PID 2只匹配1 WID(5),其總和值是2。 和PID 3匹配WID(7),其總和值是12。

我需要構建由和值執行此操作和排序查詢降。

如:

SELECT 
    index.pid, SUM(index.value) TotalSum 
FROM index 
WHERE 
    index.wid = 5 or index.wid = 7 
GROUP BY UNIQUE(index.pid) 
ORDER BY TotalSum DESC 

我知道這個查詢是不正確,但我想證明什麼,我試圖完成。

回答

0

你試圖完成的是大致正確的。

如下嘗試:

SELECT index.pid, SUM(index.value) TotalSum 
FROM index 
WHERE (wid = 5 or wid = 7) //if you want only from wid 5,7 elase no need for it 
GROUP BY index.pid 
ORDER BY TotalSum DESC 
+0

哦,我猜SUM操作確實存在笑。謝謝,讓我解決它! – nick 2012-03-04 01:08:38