作者wskevin (kevin)
看板Database
標題[SQL ] 分組查詢比較的問題…
時間Wed Jul 22 13:00:16 2009
我製作了一個表格:
mysql> select * from production;
+--------+------+----------+
| name | pid | orderqty |
+--------+------+----------+
| john | 1 | 20 |
| kevin | 2 | 10 |
| alisha | 3 | 5 |
| kevin | 2 | 30 |
| john | 3 | 15 |
+--------+------+----------+
接著,我想要以pid(產品代碼)為分組,找出組內的最大數。
mysql> select p1.pid,max(p1.orderqty) as max from production p1 group by
p1.pid;
+------+------+
| pid | max |
+------+------+
| 1 | 20 |
| 2 | 30 |
| 3 | 15 |
+------+------+
OK,到目前為止都正確…
接著,我要秀出所有的orderqty 乘以 0.9後的值,如下
mysql> select 0.9*p2.orderqty from production p2;
+-----------------+
| 0.9*p2.orderqty |
+-----------------+
| 18.0 |
| 9.0 |
| 4.5 |
| 27.0 |
| 13.5 |
+-----------------+
接著,我下了如下的指令:即組內的最大值,必需大於所有的orderqty*0.9後的值,
mysql> select p1.pid,max(p1.orderqty) as max from production p1 group by p1.pid
having max(p1.orderqty) > ALL(select 0.9*p2.orderqty from production p2 where
p1.pid=p2.pid);
原本我預期的結果為:
+------+------+
| pid | max |
+------+------+
| 2 | 30 |
+------+------+
因為,只有這一筆資料是大於所有的 0.9*p2.orderqty
但實際上的執行結果卻是:
+------+------+
| pid | max |
+------+------+
| 1 | 20 |
| 2 | 30 |
| 3 | 15 |
+------+------+
我覺得很奇怪,怎麼想都想不出哪些出錯了,
請問有誰看得出來,問題出在哪嗎?
謝謝!!!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 125.233.65.235
1F:推 bobju:你後面的子查詢裏的p1似乎出現得有點突然..結構怪怪的. 07/22 13:12
2F:推 arrack:拿掉where p1.pid=p2.pid,否則你同組最大值當然一直大於同 07/22 13:22
3F:→ wskevin:請問樓上是指,同組的所有值嗎? 07/22 13:45
4F:→ wskevin:請問有沒有方法把0.9*p2.orderqty的值秀出來? 07/22 14:24
5F:推 sai25:我會把ALL改為用MAX 這樣可以SHOW最大的0.9*p2.orderqty出來 07/22 14:33
6F:推 Antzzz:where拿掉+1。另外,用all的話,只要有一筆null就全部選不到 07/22 18:48
7F:→ wskevin:感謝大家為小弟解惑~~ 07/23 06:53