【问题标题】:Join table to CTE and group by将表加入 CTE 并分组
【发布时间】:2022-06-15 04:38:28
【问题描述】:

我有一个包含大量连接和条件的 CTE (mydashboard) 和 我正在尝试将 CTE 加入另一个表并显示一个包含第二个表计数的附加列。

我做错了什么?

select *, count(t_KPIRespConn.RespID)
from mydashboard
join t_kpirespconn on mydashboard.kpicodeid = t_kpirespconn.kpicodeid
group by mydashboard.KPIcodeID

选择列表中的列“mydashboard.code”无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

谢谢

【问题讨论】:

  • 1) 您的代码中没有 CTE。 2)该错误是不言自明的,您必须分组或汇总要在分组时显示的每一列。可能(正确地)您已经简化了您的问题,但在这种情况下,您不需要提及 CTE,因为它只是令人困惑,而且不相关。
  • 您的 CTE 定义在哪里?我猜它不仅仅是一个名为 KPIcodeID 的列。

标签: sql sql-server common-table-expression


【解决方案1】:

您将需要按所有非聚合字段进行分组,这意味着 SELECT 列表中未在聚合函数中使用的所有字段,在您的情况下,除 t_KPIRespConn.RespID 之外的所有字段。

解决方案 1:

select field1, field2, field3,... fieldN, count(t_KPIRespConn.RespID)
from mydashboard
join t_kpirespconn on mydashboard.kpicodeid = t_kpirespconn.kpicodeid
group by mydashboard.KPIcodeID, field1, field2, field3, ...fieldN

使用窗口函数基本上可以实现相同的目的,但它不那么冗长。您不需要GROUP BY,因为窗口函数会聚合指定分区上的值。对于COUNT(),可以指定OVER(),表示组中的整个结果集。

解决方案 2:

select *, 
count(*) OVER() //<-- Use this if you want the count of all records
from mydashboard
join t_kpirespconn on mydashboard.kpicodeid = t_kpirespconn.kpicodeid    

使用相同的窗口函数,但将分区缩小到您想要的任何分组。在这种情况下,计数将与具有匹配 t_KPIRespConn.RespID 值的所有记录相关。

解决方案 3:

 select *, count(*) OVER(PARTITION BY t_KPIRespConn.RespID) //<-- Use this if you want the count of all records with the same t_KPIRespConn.RespID
 from mydashboard
 join t_kpirespconn on mydashboard.kpicodeid = t_kpirespconn.kpicodeid    

【讨论】:

  • 当然这两种解决方案返回完全不同的结果,所以这真的取决于 OP 正在寻找什么结果。
  • @DaleK - 是的,我看到了。我添加了一个解决方案 3 作为示例,以将计数划分为特定的分组。
【解决方案2】:

select * .. group by mydashboard.KPIcodeID 是你真正的问题。运行聚合函数时,必须显式提供分组依据的选择列表中未聚合的任何列。这将起作用

select mydashboard.KPIcodeID, count(t_KPIRespConn.RespID)
from mydashboard
join t_kpirespconn on mydashboard.kpicodeid = t_kpirespconn.kpicodeid
group by mydashboard.KPIcodeID

【讨论】:

    猜你喜欢
    • 2019-08-16
    • 2023-03-19
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 2012-04-25
    相关资源
    最近更新 更多