【发布时间】:2020-01-17 18:13:45
【问题描述】:
我有以下 SQL 查询:
SELECT TOP 3 accounts.username
,COUNT(accounts.username) AS count
FROM relationships
JOIN accounts ON relationships.account = accounts.id
WHERE relationships.following = 4
AND relationships.account IN (
SELECT relationships.following
FROM relationships
WHERE relationships.account = 8
);
我想返回accounts.username 和前3 个accounts.username 的总数(没有特别的顺序)。不幸的是accounts.username 和COUNT(accounts.username) 不能共存。该查询可以很好地删除其中一个。我不想使用不同的选择主体两次发送请求。计数列可以跨越到 1000+,所以我更愿意在 SQL 中而不是在代码中计算它。
当前查询返回错误Column 'accounts.username' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.,它没有带我到任何地方,这与其他问题不同,因为我不想使用“分组依据”子句。有没有办法用FOR JSON AUTO 做到这一点?
所需的输出可能是:
+-------+----------+
| count | username |
+-------+----------+
| 1551 | simon1 |
| 1551 | simon2 |
| 1551 | simon3 |
+-------+----------+
或
+----------------------------------------------------------------+
| JSON_F52E2B61-18A1-11d1-B105-00805F49916B |
+----------------------------------------------------------------+
| [{"count": 1551, "usernames": ["simon1", "simon2", "simon3"]}] |
+----------------------------------------------------------------+
【问题讨论】:
-
我完全不明白你想要什么。你能提供一个minimal reproducible example 让每个人都知道你想要完成什么吗?
标签: sql sql-server tsql