我们有三张桌子:
p:
<`
+-----+-------+-------+--------+--------+
| pno | pname | color | weight | city |
+-----+-------+-------+--------+--------+
| p1 | nut | red | 12 | London |
| p2 | bolt | green | 17 | Paris |
| p3 | screw | blue | 17 | Rome |
| p4 | screw | red | 14 | London |
| p5 | cam | blue | 12 | Paris |
| p6 | cog | red | 19 | London |
+-----+-------+-------+--------+--------+
`
s:
+-----+-------+--------+--------+
| sno | sname | status | city |
+-----+-------+--------+--------+
| s1 | Smith | 20 | London |
| s2 | Jones | 10 | Paris |
| s3 | Blake | 30 | Paris |
| s4 | Clark | 20 | London |
| s5 | Adams | 30 | Athens |
+-----+-------+--------+--------+
sp:
+-----+-----+-----+
| sno | pno | qty |
+-----+-----+-----+
| s1 | p1 | 300 |
| s1 | p2 | 200 |
| s1 | p3 | 400 |
| s1 | p4 | 200 |
| s1 | p5 | 100 |
| s1 | p6 | 100 |
| s2 | p1 | 300 |
| s2 | p2 | 400 |
| s3 | p2 | 200 |
| s4 | p2 | 200 |
| s4 | p4 | 300 |
| s4 | p5 | 400 |
+-----+-----+-----+
我们需要完成的任务:让GRTQ为供应商编号为Si的每个供应商发运的任何种类的绿色和红色部分的总量。获得包含元组的表,其中GRTQ> 300.按总量的递增顺序列出结果。
有什么好主意吗?我很快就会发布一些尝试。
答案 0 :(得分:2)
试试这个:
SELECT
s.sno,
s.sname,
SUM(sp.qty) AS `GRTQ`
FROM
sp
INNER JOIN
s
ON
s.sno = sp.sno
INNER JOIN
p
ON
p.pno = sp.pno
WHERE
(p.color = 'red' or p.color = 'green')
GROUP BY
s.sno,
s.sname
HAVING
`GRTQ` > 300
ORDER BY
`GRTQ` ASC
这是样本数据的输出:
+------+-------+------+
| sno | sname | GRTQ |
+------+-------+------+
| s1 | Smith | 800 |
| s2 | Jones | 1400 |
+------+-------+------+
2 rows in set (0.00 sec)
答案 1 :(得分:2)
这是您的查询:
SELECT s.sno, SUM(sp.qty) as GRTQ
FROM s, p, sp
WHERE s.sno = sp.sno AND p.pno = sp.pno AND (p.color = "red" OR p.color="green")
GROUP BY s.sno, s.sname
HAVING GRTQ > 300
ORDER BY GRTQ ASC;
The resulting output is:
+-----+------+
| sno | GRTQ |
+-----+------+
| s4 | 500 |
| s2 | 700 |
| s1 | 800 |
+-----+------+
您可以自行计算来验证它。
即。红色或绿色部分是p1,p2,p4,p6
其中:
s4仅提供p2和p4,分别为200和300。总计= 500
s2仅提供p1和p2,数量分别为300和400。总计= 700
s1提供了以下数量的所有部件:300 + 200 + 200 + 100.总计= 800