简体   繁体   English

sql-以特定格式获取每个年级的员工人数

[英]sql - getting the count of employee in each grade in a specific format

I am new to sql ,I have a table like this 我是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

I need to get the count of the employee in each grade , in which the final ouput will be "2 - 2 - 2 - 1 " in a single column where output refers (Count of Employee in each Grade ie A1(2) - A2(2)- A3(2) -A4(1)) . 我需要获取每个年级的员工数,其中最终输出将是输出所指向的单列中的“ 2-2-2-1”(每个年级的员工数,即A1(2)-A2 (2)-A3(2)-A4(1))。 can anyone give sql query for this. 任何人都可以为此提供sql查询。 I hope we dont need cursor for this . 我希望我们不需要光标。

SELECT COUNT(Emp_id) FROM myTableName GROUP BY EMP_GRADE
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 Fiddle example SQL Fiddle示例


If you are filtering but still want to return results for every grade, you will need a self-join to get the full list of grades. 如果您正在过滤,但仍想返回每个年级的结果,则将需要一个自我联接才能获得完整的年级列表。 Here's one way: 这是一种方法:

;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 Fiddle example SQL Fiddle示例

Use: 采用:

   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

Update: 更新:

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

This should work: 这应该工作:

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

Hope that helps. 希望能有所帮助。 Keep learning SQL. 继续学习SQL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM