我无法理解这个问题。我有一个客户-员工沟通系统。在管理方面,我试图检索用户列表,其中包含该用户的消息总数、新消息总数、最后一条消息日期、最后一条消息。
一点逻辑:
- sender或receiver值为0,表示工作人员发送或接收。
- 发送方或接收方值为 X,表示 ID 值为 X 的用户接收或发送了该消息。
示例数据:
ID |date |new |sender |receiver |message
----+-----------------------+-------+-------+-----------+------------
1 |2013-12-22 08:19:12 |1 |2 |0 |Hello
2 |2013-12-22 08:23:19 |0 |0 |2 |Hello There
3 |2013-12-22 08:23:19 |0 |0 |4 |Hello There
4 |2013-12-22 10:09:44 |1 |2 |0 |The latest message
期望的输出:
user ID |total_messages |total_new |latest_date |latest_messsage
------------------------------------------------------------------------------
2 |3 |2 |2013-12-22 10:09:44 |The latest message
4 |1 |0 |2013-12-22 08:23:19 |Hello There
我使用的是 SQL Server 2008
最佳答案
在两个查询中拆分选择第一行和聚合行的逻辑,并对结果进行 UNION 操作。
SELECT TOP 1 --columns--
FROM yourTable
UNION ALL
SELECT --columns--
FROM yourTable
GROUP BY --columns--
(没有有关表结构或所需输出的更多详细信息,这是我能想到的最佳答案)
关于SQL SELECT 顶行和聚合计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20728655/