作者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