sql - SQL Server:Group By 导致“列无效”错误,如何解决?
问题描述
我正在尝试根据上次更新的机会(使用:)过滤cg_group
名称(请检查查询)和分组(使用:)结果。GROUP BY
ORDER BY opportunities.date_modified DESC
当我使用不使用 group by 的查询时,它返回以下结果:
SELECT cg_groups.name
FROM cg_groups
JOIN cg_groups_cstm ON cg_groups_cstm.id_c = cg_groups.id
JOIN accounts_cstm ON cg_groups.name = accounts_cstm.client_group_c
JOIN accounts ON accounts.id = accounts_cstm.id_c
JOIN accounts_opportunities ON accounts.id = accounts_opportunities.account_id
JOIN opportunities ON accounts_opportunities.opportunity_id = opportunities.id
WHERE cg_groups.deleted='0' AND cg_groups_cstm.status_c='1' AND opportunities.deleted='0'
ORDER BY opportunities.date_modified DESC
结果:
ABC Group
ABC Group
CBC Group
ABC Group
XYZ Group
但我想按以下顺序分组:
ABC Group
CBC Group
XYZ Group
为此,我添加了GROUP BY cg_groups.name
SELECT cg_groups.name
FROM cg_groups
JOIN cg_groups_cstm ON cg_groups_cstm.id_c = cg_groups.id
JOIN accounts_cstm ON cg_groups.name = accounts_cstm.client_group_c
JOIN accounts ON accounts.id = accounts_cstm.id_c
JOIN accounts_opportunities ON accounts.id = accounts_opportunities.account_id
JOIN opportunities ON accounts_opportunities.opportunity_id = opportunities.id
WHERE cg_groups.deleted='0' AND cg_groups_cstm.status_c='1' AND opportunities.deleted='0'
GROUP BY cg_groups.name
ORDER BY opportunities.date_modified DESC
但现在我得到这个错误:
消息 8127,级别 16,状态 1,第 10
行列“opportunities.date_modified”在 ORDER BY 子句中无效,因为它不包含在聚合函数或 GROUP BY 子句中。
有人请帮我解决这个问题,谢谢。
解决方案
distinct
在你的SELECT
陈述之后添加怎么样。
Select distinct ... from ...
推荐阅读
- c# - 从列表中生成 EF 模型中的多个列
- android - kotlin.NotImplementedError: 未使用 EditText 上的 addTextChangedListenerher 实现操作
- javascript - 如何在 Django for 循环中使用“单击”选择一个元素而不是所有元素
- r - R:write.dbf() 更改我的数据框列的名称
- visual-studio - 为什么 Visual Studio 在构建时没有注意到 packages.config 的更改?
- c# - 如何对导入的 PDF 模态进行断言或验证?
- python - python aiohttp中间件func定义;为什么有区别,什么是最好的
- c# - 如何从一种类型序列化/反序列化到另一种类型?
- colors - Vulkan - 浮点着色器颜色值到读取缓冲区中的 uchar 值的奇怪映射
- vba - 如何创建一个从位于同一工作表但位置不同的表中添加值的列表