テーブルは部門ごとにグループ化する必要があり、部門の最大量を返す必要があります
表A:
Id | 名前 | 部門 |
---|---|---|
1 | ジョン・エイブラハム | 人事 |
2 | マイケルクラーク | 人事 |
3 | ロイトーマス | マネージャー |
4 | トム・ホセ | 人事 |
4 | ジェリーピント | マネージャー |
表B:
M_Id | 量 |
---|---|
1 | 5000 |
2 | 5000 |
3 | 2500 |
4 | 1000 |
4 | 1500 |
期待される答え
Id | 名前 | 部門 | 量 |
---|---|---|---|
1 | ジョン・エイブラハム | 人事 | 5000 |
2 | マイケルクラーク | 人事 | 5000 |
3 | ロイトーマス | マネージャー | 2500 |
あなたはこのようなことを試すことができます:
select main.*
FROM
-- get all information from t1 and amount from t2
(
select t1.*, t2.amount from t1 inner join t2 on t1.id = m_id
) main
INNER JOIN
-- get max amount by department
(
select department, max(amount) max_amount from t1 inner join t2 on t1.id = m_id
group by department
) summary
-- match with main by department and the max amount
on main.department = summary.department
and main.amount = summary.max_amount;
結果
+------+----------------+------------+--------+
| id | name | department | amount |
+------+----------------+------------+--------+
| 1 | John Abraham | HR | 5000 |
| 2 | Michael Clarke | HR | 5000 |
| 3 | Roy Thomas | Manager | 2500 |
+------+----------------+------------+--------+
例はここにあります:https://dbfiddle.uk/?rdbms = mysql_5.7&fiddle = a4cdd94b415df204b0fd967263ba9dc8
説明
部門ごとに最大額を取得したいので、そのためのサブクエリを作成しました。エイリアスを付けましたsummary
。それは私たちにこれを与えました:
select department, max(amount)
from t1 inner join t2 on t1.id = m_id group by department;
+------------+-------------+
| department | max(amount) |
+------------+-------------+
| HR | 5000 |
| Manager | 2500 |
+------------+-------------+
t1テーブルとt2テーブルを組み合わせて、レポートするデータを組み合わせ、エイリアスを付けましたmain
。それは私たちにこれを与えました:
select t1.*, t2.amount from t1 inner join t2 on t1.id = m_id;
+------+----------------+------------+--------+
| id | name | department | amount |
+------+----------------+------------+--------+
| 1 | John Abraham | HR | 5000 | <-- want this
| 2 | Michael Clarke | HR | 5000 | <-- want this
| 3 | Roy Thomas | Manager | 2500 | <-- want this
| 4 | Jerry Pinto | Manager | 1000 |
| 4 | Tom Jose | HR | 1000 |
+------+----------------+------------+--------+
次に、部門と両方のサブクエリの金額に基づいて、両方のサブクエリが結合されていることを確認しました。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加