これを試して:
SELECT
t.ticket_id,
ticket_desc,
ht.status
FROM ticket AS t
INNER JOIN history_ticket AS ht ON t.ticket_id = ht.ticket_id
INNER JOIN
(
SELECT ticket_id, MAX(history_id) maxid
FROM history_ticket
GROUP BY ticket_id
) AS ht2 ON ht.history_id = ht2.maxid;
これにより、次のことが得られます。
| TICKET_ID | TICKET_DESC | STATUS |
-------------------------------------
| 1 | software | process |
| 2 | hardware | solve |
| 3 | Problem | solve |
更新 1
COUNT(history_id) AS sum_message
各チケットのメッセージ数を取得するには、次のようにサブクエリに含めるだけです。
SELECT
t.ticket_id,
ticket_desc,
ht.status,
ht2.sum_message
FROM ticket AS t
INNER JOIN history_ticket ht ON t.ticket_id = ht.ticket_id
INNER JOIN
(
SELECT
ticket_id,
MAX(history_id) maxid,
COUNT(history_id) AS sum_message
FROM history_ticket
GROUP BY ticket_id
) AS ht2 ON ht.history_id = ht2.maxid;
これにより、次のことが得られます。
| TICKET_ID | TICKET_DESC | STATUS | SUM_MESSAGE |
---------------------------------------------------
| 1 | software | process | 1 |
| 2 | hardware | solve | 1 |
| 3 | Problem | solve | 2 |
更新 2
divisi_id
単純な値の ids の名前を選択する場合は、次のCASE
式を使用できます。
SELECT
t.ticket_id,
ticket_desc,
CASE
WHEN t.divisi_id = 101 THEN 'Divisi A'
WHEN t.divisi_id = 102 THEN 'Divisi B'
END AS 'Divisi',
ht.status,
ht2.sum_message
FROM ticket AS t
INNER JOIN history_ticket ht ON t.ticket_id = ht.hticket_id
INNER JOIN
(
SELECT hticket_id, MAX(history_id) maxid, COUNT(history_id) AS sum_message
FROM history_ticket
GROUP BY hticket_id
) AS ht2 ON ht.history_id = ht2.maxid;
これにより、次のことが得られます。
| TICKET_ID | TICKET_DESC | DIVISI | STATUS | SUM_MESSAGE |
--------------------------------------------------------------
| 1 | software | Divisi A | process | 1 |
| 2 | hardware | Divisi B | solve | 1 |
| 3 | Problem | Divisi A | solve | 2 |
複数の値の場合、それらを一時テーブルに入れるか、サブクエリでそれらを選択してテーブルを結合して、次のような名前を取得できます。
SELECT
t.ticket_id,
ticket_desc,
d.Divisi,
ht.status,
ht2.sum_message
FROM ticket AS t
INNER JOIN history_ticket ht ON t.ticket_id = ht.hticket_id
INNER JOIN
(
SELECT hticket_id, MAX(history_id) maxid, COUNT(history_id) AS sum_message
FROM history_ticket
GROUP BY hticket_id
) AS ht2 ON ht.history_id = ht2.maxid
INNER JOIN
(
SELECT 101 AS divisi_id, 'Divisi A' AS Divisi
UNION ALL
SELECT 102 , 'Divisi B'
... -- here you put other values or you can join a temp table instead
) AS D ON t.divisi_id = D.divisi_id;