SELECT
a.questionId,
a.firstname
FROM
(
SELECT q.questionId, u.firstname, u.lastname, q.createdDate FROM HR_CALLCENTER.dbo.question AS q
INNER JOIN HR_CALLCENTER.dbo.users AS u ON q.createdId = u.employeeId
UNION
SELECT r.questionId, u.firstname, u.lastname, r.createdDate FROM HR_CALLCENTER.dbo.reply AS r
INNER JOIN HR_CALLCENTER.dbo.users AS u ON r.createdId = u.employeeId
) AS a
GROUP BY a.questionId
ถ้าต้องการแค่ GROUP BY a.questionId ทํายังไงได้บ้างครับเพราะ MSSQL มันจะบังคับให้ GROUP BY firstname ด้วย
SELECT
DISTINCT
a.questionId,
a.firstname
FROM
(
SELECT q.questionId, u.firstname, u.lastname, q.createdDate FROM HR_CALLCENTER.dbo.question AS q
INNER JOIN HR_CALLCENTER.dbo.users AS u ON q.createdId = u.employeeId
UNION
SELECT r.questionId, u.firstname, u.lastname, r.createdDate FROM HR_CALLCENTER.dbo.reply AS r
INNER JOIN HR_CALLCENTER.dbo.users AS u ON r.createdId = u.employeeId
) AS a
SELECT
DISTINCT
a.questionId,
a.firstname,
MAX(q.createdDate) AS createdDate
FROM
(
SELECT q.questionId, u.firstname, u.lastname, q.createdDate FROM HR_CALLCENTER.dbo.question AS q
INNER JOIN HR_CALLCENTER.dbo.users AS u ON q.createdId = u.employeeId
UNION
SELECT r.questionId, u.firstname, u.lastname, r.createdDate FROM HR_CALLCENTER.dbo.reply AS r
INNER JOIN HR_CALLCENTER.dbo.users AS u ON r.createdId = u.employeeId
) AS a
GROUP BY a.questionId, a.firstname