【问题标题】:How to Use count and Group By with Self join in the same table in sql server 2008?如何在 sql server 2008 的同一张表中使用计数和分组方式和自连接?
【发布时间】:2013-11-07 02:59:47
【问题描述】:

我有一个包含st_nameid 列的表。我需要得到st_name 的计数并按st_name 分组。我该怎么做?

【问题讨论】:

  • 请添加示例数据和所需结果。
  • 站名 | ID val1 1 val2 2 以上是表格格式。需要通过 ID 获取 Station_name Group 的计数。我的查询是:select station_name,count(*) as grp_cnt, (select count(distinct station_name) from tbl_Training_Detail) as st_cnt from tbl_Training_Detail group by MasterId
  • @Suren:这很难读。请编辑您的答案以添加您的 CREATE TABLE 脚本和您迄今为止的最佳尝试。请注意,如果您缩进代码,它将被格式化(例如,使用固定宽度的字体)。

标签: sql sql-server-2008 aggregate-functions


【解决方案1】:
select st_name, 
       count(*) as grp_cnt,
       (select count(distinct st_name) from your_table) as st_cnt
from your_table
group by st_name

【讨论】:

  • count(*) OVER() AS st_cnt 也会做同样的事情。
  • 欢呼 Juergen,但我需要使用 ID 而非 st_name 进行分组。使用 ID 分组运行时出现此错误:列 'tbl_Training_Detail.Station_Name' 在选择列表中无效,因为它不包含在内在聚合函数或 GROUP BY 子句中。
  • @SurendarCBE:那么请更新您的问题以明确您要做什么,并添加示例数据。
  • 站名 | ID val1 1 val2 2 以上是表格格式。需要通过 ID 获取 Station_name Group 的计数。我的查询是:select station_name,count(*) as grp_cnt, (select count(distinct station_name) from tbl_Training_Detail) as st_cnt from tbl_Training_Detail group by MasterId
  • @Suren:正如我所说,请以格式正确的方式将其添加到您的问题中。
猜你喜欢
  • 2012-04-07
  • 2020-11-16
  • 2012-06-05
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多