3

Messages在 SQL Server 2012 中有一个表。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 中引入的新 windows 功能来提高效率。我该怎么做 ?

4

4 回答 4

4

请检查这是否有帮助。

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

或者您可以在两列中进行选择,例如:

SELECT  SUM(IsRead - 0) AS ReadCount,
        SUM(1 - IsRead) AS UnreadCount
FROM    YourTable
于 2013-02-01T09:36:02.973 回答
2
SELECT  COUNT(CASE WHEN isRead = 1 THEN 1 END) AS read,
        COUNT(CASE WHEN isRead = 0 THEN 1 END) AS unread
FROM    mytable
于 2013-02-01T09:38:03.643 回答
1

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

这里还有另一种方法,你可以得到你的解决方案

SELECT (SELECT COUNT(isRead) FROM [mytable] WHERE isRead = 1) AS READDATA,
(SELECT COUNT(isRead) FROM [mytable] WHERE isRead = 0) AS UNREADDATA
于 2013-02-01T09:51:23.453 回答
-1

选择 IsRead, count(*) from Messages Group by IsRead 但输出将是 2 行。

于 2013-02-01T09:35:42.540 回答