如何通过查询区分联合/分组的记录

时间:2011-10-27 01:55:51

标签: sql sql-server

第一个高级别:

我有一个网页,它会显示用户与他或她所接触过的每个人之间的对应关系,但只显示他们与其他人之间的最后对应关系,从而产生一个独特的用户列表。

问题是我把它们全部联合在一起并对它们进行分组但却无法区分任何记录。我不知道是谁发送了邮件,或者是电子邮件还是即时消息。

我想过创建一个像

这样的虚拟列
'received' AS SentReceived
'sent' AS SentReceived
'email' AS CorrespondanceType
'instant_message' AS CorrespondanceType

然后我失去了我的意识。

为了简洁起见,我会提出一些简明扼要的sql概述我在哪里:

SELECT username, CorrespondanceType, SentReceived, MAX(Date) FROM (
SELECT username, 'email' AS CorrespondanceType, 'received' AS SentReceived, Date FROM tbl_email WHERE user_id='1'
SELECT username, 'email' AS CorrespondanceType, 'sent' AS SentReceived, Date FROM tbl_email WHERE user_id='1'
SELECT username, 'instant_message' AS CorrespondanceType, 'received' AS SentReceived, Date FROM tbl_instant_message WHERE user_id='1'
SELECT username, 'instant_message' AS CorrespondanceType, 'sent' AS SentReceived, Date FROM tbl_instant_message WHERE user_id='1'
) AS tbl_correspondance_summary
GROUP BY username

因此,如果我不使用虚拟列,如何确定对应类型以及发送者是谁,如果我使用它们,如何使我的结果在用户名上消失?

这是SQL Server,顺便说一句

1 个答案:

答案 0 :(得分:0)

with RowNumbers as (
    SELECT username, CorrespondanceType, SentReceived, Date,
      ROW_NUMBER() OVER (partition by username order by Date desc) as RowNum
    FROM (
    SELECT username, 'email' AS CorrespondanceType, 'received' AS SentReceived, Date FROM tbl_email WHERE user_id='1'
    SELECT username, 'email' AS CorrespondanceType, 'sent' AS SentReceived, Date FROM tbl_email WHERE user_id='1'
    SELECT username, 'instant_message' AS CorrespondanceType, 'received' AS SentReceived, Date FROM tbl_instant_message WHERE user_id='1'
    SELECT username, 'instant_message' AS CorrespondanceType, 'sent' AS SentReceived, Date FROM tbl_instant_message WHERE user_id='1'
    ) AS tbl_correspondance_summary
)

select * from RowNumbers where RowNum = 1