我很确定你们有一个简单而快速的解决方案来解决我的问题,但我的SQL技能是有限的,我不能自己解决。
所以我拥有的是:
新闻组:[姓名(PK)]
文章:[Id(PK)] [newsgroupName(FK)] [date:Date] [read:Boolean]
我想知道的是一个查询,它给出了每个新闻组的名称以及未读文章的数量,所有文章的数量以及最新文章的日期...... 这甚至可以在单个Select-Query中实现吗?
提前谢谢你们!
答案 0 :(得分:2)
您可以简单地使用适当的聚合函数:
SELECT newsgroupName,
SUM(NOT read) AS countUnread,
COUNT(*) AS countAll,
MAX(date) AS mostRecentDate
FROM Article
GROUP BY newsgroupName;
答案 1 :(得分:0)
我猜是这样的:
SELECT name, COUNT(countUnread) AS countUnread, COUNT(countRead) AS countRead, MAX(mostRecentDateUnread) AS mostRecentDateUnread, MAX(mostRecentDateRead) AS mostRecentDateRead FROM (
SELECT newsgroupName AS name, COUNT(newsgroupName) AS countUnread, 0 AS countRead, MAX(date) AS mostRecentDateUnread, NULL AS mostRecentDateRead
FROM Article
WHERE read = 0
GROUP BY newsgroupName, read
UNION ALL
SELECT newsgroupName AS name, 0 AS countUnread, COUNT(newsgroupName) AS countRead, NULL AS mostRecentDateUnread, MAX(date) AS mostRecentDateRead
FROM Article
WHERE read = 1
GROUP BY newsgroupName, read
)
GROUP BY name
我还没有尝试,但理论上有一些修复它可以工作。