如何从多个表中获取应该最小化和分组的值
像: 我有三张桌子
Table1 Table3
| ID | GPN | PKGID | | GPN | Amt |
| 1 | A | PKG01 | | A | 10 |
| 2 | B | PKG02 | | A | 15 |
| 3 | C | PKG03 | | A | 20 |
| 4 | D | PKG04 | | A | 25 |
| A | 65 |
| A | 30 |
----------------------------- | B | 17 |
| D | 90 |
| B | 20 |
Table2 | B | 40 |
| GPN | Date | | D | 60 |
| A | 2016-09-10 | | B | 80 |
| A | 2016-09-18 | | B | 100 |
| B | 2016-09-10 | | C | 3 |
| B | 2016-09-11 | | C | 6 |
| B | 2016-09-12 | | C | 9 |
| C | 2016-10-12 | | C | 12 |
| C | 2016-10-13 | | C | 15 |
| C | 2016-10-14 | | D | 7 |
| D | 2016-09-10 | | D | 10 |
| D | 2016-10-13 | | D | 13 |
我必须从表中的三个中获取值,所以我该怎么做。
例如
日期= 2016-09-10
我必须得到代表的价值 所以结果应该包含所有组的最小值。
结果
| ID | PKGID | GPN | Amt | Date |
| 1 | PKG01 | A | 10 | 2016-09-10 |
| 2 | PKG02 | B | 17 | 2016-09-10 |
| 4 | PKG04 | D | 7 | 2016-09-10 |
答案 0 :(得分:2)
应该是这个
select table.id, table1.PKGID, table1.GPN, min(table3.Amt), table2.`date`
from table1
inner join table3 on table1.GPN= table3.GPN
inner join table2 on table1.GPN= table2.GPN
where date(table2.date ) = str_to_date('2016-09-10', '%Y-%m-%d')
group by table1.GPN, table.id, table1.PKGID, table2.`date`
答案 1 :(得分:1)
你也可以尝试这个
SELECT t1.*, MIN(t3.Amt) as Amt, t2.Date
FROM table1 t1
INNER JOIN table2 t2 on t1.GPN= t2.GPN
INNER JOIN table3 t3 on t1.GPN= t3.GPN
WHERE t2.Date = '2016-09-10'
GROUP BY t1.GPN
答案 2 :(得分:0)
你可以尝试这样的事情。首先通过分组获取MIN(Amt)
,然后执行JOIN
select t1.*,
xxx.Amt,
t2.`Date`
from table1 t1 join table2 t2 on t1.GPN = t2.GPN
join (select GPN, min(Amt) as Amt from table3 group by GPN) xxx
on t1.GPN = xxx.GPN;