0

我是 sql 新手,我有一张这样的表

Emp_id | Emp_NAME | EMP_GRADE
  1 测试1 A1
  2 测试2 A2
  3 测试3 A3
  4 测试4 A4
  6 测试5 A1
  7 测试6 A2
  8 测试7 A3

我需要获取每个年级的员工人数,其中最终输出将是“2 - 2 - 2 - 1”在输出所指的单个列中(每个年级的员工人数,即 A1(2) - A2 (2)-A3(2)-A4(1))。任何人都可以为此提供sql查询。我希望我们不需要光标。

4

4 回答 4

1
SELECT COUNT(Emp_id) FROM myTableName GROUP BY EMP_GRADE
于 2013-03-08T06:11:50.270 回答
0
SELECT STUFF((
  SELECT ' - ' + CAST(COUNT(1) AS VARCHAR(max)) 
  FROM myTable 
  GROUP BY EMP_GRADE 
  ORDER BY EMP_GRADE 
  FOR XML PATH('')
), 1, 3, '')

SQL 小提琴示例


如果您正在过滤,但仍想返回每个成绩的结果,则需要自我加入以获取完整的成绩列表。这是一种方法:

;WITH g AS (SELECT DISTINCT EMP_GRADE FROM myTable)
SELECT STUFF((
  SELECT ' - ' + CAST(COUNT(t.Emp_id) AS VARCHAR(max)) 
  FROM g
  LEFT OUTER JOIN myTable t ON g.EMP_GRADE = t.EMP_GRADE
      AND t.Emp_id % 2 = 1 --put your filter conditions here as part of the join
  GROUP BY g.EMP_GRADE
  ORDER BY g.EMP_GRADE
  FOR XML PATH('')
), 1, 3, '')

SQL 小提琴示例

于 2013-03-08T06:08:43.060 回答
0

采用:

   DECLARE @Grades varchar(1000)

  SELECT @Grades=coalesce(@Grades + ' ','') +Cast(COUNT(EMP_GRADE) as Varchar(2))+' -'  From TableName 
  Group By EMP_GRADE

  Select @Grades=SUBSTRING(@Grades,0,LEN(@Grades))
  Select @Grades

更新:

SELECT @Grades=coalesce(@Grades + ' ','') +Cast(COUNT(t1.EMP_GRADE) as Varchar(2))+' -'  From @tab1 t
Left Join @tab1 t1 On t1.EMP_GRADE= t.EMP_GRADE And  t1.Emp_id= t.Emp_id 
And t1.EMP_GRADE<>'A3' -- Replace conditions here
Group By t1.EMP_GRADE,t.EMP_GRADE
于 2013-03-08T06:12:02.967 回答
0

这应该有效:

SELECT EMP_GRADE, COUNT(EMP_Id) AS EMPS_COUNT
FROM TableName
GROUP BY EMP_GRADE

希望有帮助。继续学习 SQL。

于 2013-03-08T06:16:41.203 回答