在单个查询中查找已读和未读消息的计数

时间:2013-02-01 09:32:58

标签: sql sql-server

我在SQL Server 2012中有一个表Messages。 表格中有three columns

ID which is an identity column, 
MessageID (int) which is a foreign key to other table and 
IsRead field which is a bit not null column.

在给定的时间点,表格可以包含大量IsRead列值为1 or 0的记录。 我想写一个查询,在其中我在两个单独的列中找到读取和未读消息的计数。 我正在尝试使用SQL Server 2012中引入的新窗口功能来提高效率。 我该怎么办?

4 个答案:

答案 0 :(得分:3)

请检查这是否有帮助。

SELECT 
    IsRead, 
    COUNT(*) ReadCount 
FROM 
    YourTable 
GROUP BY IsRead

或者您可以选择两列,如:

SELECT  SUM(IsRead - 0) AS ReadCount,
        SUM(1 - IsRead) AS UnreadCount
FROM    YourTable

答案 1 :(得分:2)

SELECT  COUNT(CASE WHEN isRead = 1 THEN 1 END) AS read,
        COUNT(CASE WHEN isRead = 0 THEN 1 END) AS unread
FROM    mytable

答案 2 :(得分:1)

@Quassnoi 提到的查询很简单.............

此处还有一种方法可以让您获得解决方案

SELECT (SELECT COUNT(isRead) FROM [mytable] WHERE isRead = 1) AS READDATA,
(SELECT COUNT(isRead) FROM [mytable] WHERE isRead = 0) AS UNREADDATA

答案 3 :(得分:-1)

从IsRead的Messages Group中选择IsRead,count(*) 但输出将是2行。