具有相同字段且具有不同多个状态的行数

时间:2018-02-14 07:10:32

标签: sql sql-server

下面是我有部门名称及其风险的表格

enter image description here

我希望计算出对姓名的风险。我在SQL Server中这样做。

3 个答案:

答案 0 :(得分:3)

您可以在此处使用条件聚合:

SELECT DepartmentName,
        SUM(CASE WHEN Risk = 'High' THEN 1 ELSE 0 END) High,
        SUM(CASE WHEN Risk = 'Medium' THEN 1 ELSE 0 END) Medium,
        SUM(CASE WHEN Risk = 'Low' THEN 1 ELSE 0 END) Low
FROM    TableName
GROUP BY DepartmentName

答案 1 :(得分:1)

SELECT * FROM
(
  SELECT DEPARTMENT_NAME,RISK
  FROM YOUR_TABLE order by RISK 
)
PIVOT
(
COUNT(RISK) AS COUNT1
FOR  RISK IN ('HIGH', 'LOW', 'MEDIUM')
);

答案 2 :(得分:0)

您也可以使用pivot。假设您有更多的风险值,您可以使用以下查询动态地执行此操作

SET NOCOUNT ON 
IF OBJECT_ID ('tempdb..##Table') IS NOT NULL DROP TABLE ##Table

CREATE TABLE ##Table (DepartmentName NVARCHAR(100) , Risk NVARCHAR(20))
INSERT INTO ##Table (DepartmentName , Risk)
VALUES ('BPO' , 'High'),
       ('BPO' , 'Medium'),
       ('BPO' , 'Low'),
       ('BPO' , 'High'),
       ('Domains' , 'High'),
       ('BPO' , 'High'),
       ('Bank Reconciliation' , 'High'),
       ('Godownsss' , 'High'),
       ('BPO' , 'High')

  DECLARE @Cols NVARCHAR(2000)= ''
  DECLARE @PvT NVARCHAR(MAX)=''
  SELECT @Cols += ',' +QUOTENAME(Risk)
  FROM ##Table 
  GROUP BY QUOTENAME(Risk)

  SET @Cols = STUFF(@Cols,1,1,'')

  SET @PvT = 'SELECT DepartmentName , ' +@Cols+'
                FROM ##Table t
                    PIVOT 
                    (
                    COUNT(Risk) FOR Risk IN ('+@Cols+')
                    ) P
                '
  EXEC sp_executesql @Pvt