Sql 如何根据查询区分记录与联合/分组记录
第一个高级别: 我有一个网页,它将显示用户和他或她接触过的每个人之间的对应关系,但只显示他们和其他人之间的最后一次对应关系,从而产生一个不同的用户列表 问题是我把所有的唱片都联合在一起,并将它们分组,但无法区分任何唱片。我不知道是谁发的消息,也不知道是电子邮件还是即时消息 我想创建一个虚拟列,如Sql 如何根据查询区分记录与联合/分组记录,sql,sql-server,Sql,Sql Server,第一个高级别: 我有一个网页,它将显示用户和他或她接触过的每个人之间的对应关系,但只显示他们和其他人之间的最后一次对应关系,从而产生一个不同的用户列表 问题是我把所有的唱片都联合在一起,并将它们分组,但无法区分任何唱片。我不知道是谁发的消息,也不知道是电子邮件还是即时消息 我想创建一个虚拟列,如 'received' AS SentReceived 'sent' AS SentReceived 'email' AS CorrespondanceType 'instant_message' AS
'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,顺便说一句啊,很好,我做到了。刚刚做了编辑。谢谢!在您的表中,如何区分发送的消息和接收的消息?使用发送者id和接收者id,但实际上我将它们分别命名为用户id和成员id,用户id始终是登录用户,成员id是“另一个人”。我没有把这些放在上面只是为了简化这一切。在.netow中构建sql查询时,我通过在where子句中动态指定发送者或接收者来实现这一点,这是有效的。我还不完全明白,但它奏效了!谢谢
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