SQL - 让员工的数量每级以特定格式(sql - getting the count of em

2019-10-17 18:48发布

我是新来的sql,我有这样的一个表

Emp_id    |  Emp_NAME | EMP_GRADE
  1           Test1      A1
  2           Test2      A2
  3           Test3      A3
  4           Test4      A4
  6           Test5      A1
  7           Test6      A2
  8           Test7      A3

我需要得到在每个等级的雇员,其中最终输出中会的计数“2 - 2 - 2 - 1”在单个列中,其中输出是指在每个级,即A1(员工的计数(2) - A2 (2) - A3(2)-A4(1))。 谁能给SQL查询这一点。 我希望我们不需要光标这一点。

Answer 1:

采用:

   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


Answer 2:

SELECT COUNT(Emp_id) FROM myTableName GROUP BY EMP_GRADE


Answer 3:

这应该工作:

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

希望帮助。 不断地学习SQL。



Answer 4:

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例如拨弄



文章来源: sql - getting the count of employee in each grade in a specific format