根据多行值填充结果列

时间:2019-12-04 17:15:00

标签: sql

我需要能够使用状态值将输出汇总成一行来分析多行,如下所示: 我有这张桌子

+------+--------------+
| EmployeeID|   Status| 
+---------------------+
| 997624    | complete|
| 997624    | complete|
| 997624    | complete|
| 556723    | complete| 
| 556723  |incomplete |
| 556723    | complete|
| 556723 | incomplete |
+------+--------------+

我希望能够运行查询以将该表汇总为以下内容 如果员工全部完成,结果将是

+------+--------------+
| EmployeeID|   Status| 
+---------------------+
| 997624    | complete|

但是如果雇员只有一个不完整,那么他的结果将是不完整的

+------+--------------+
| EmployeeID|   Status| 
+---------------------+
| 556723 | incomplete|

我该怎么做?

3 个答案:

答案 0 :(得分:1)

如果表中只有值model.summarycomplete可用,则应该这样做:

incomplete

之所以有效,是因为select employee_id, max(status) status from mytable group by employee_id

否则,您可以执行以下操作:

'incomplete' > 'complete'

答案 1 :(得分:0)

请尝试以下操作:

IF (OBJECT_ID('tempdb..#my_emp_table') IS NOT NULL)
BEGIN
   DROP TABLE #my_emp_table
END;


CREATE TABLE #my_emp_table (EmployeeID INT NOT NULL, [STATUS] nvarchar(max) NULL);

INSERT INTO #my_emp_table([EmployeeID], [STATUS])
       VALUES  (997624,'complete')
              ,(997624,'complete')
              ,(997624,'complete')
              ,(556723,'complete') 
              ,(556723,'incomplete')
              ,(556723,'complete')
              ,(556723,'incomplete')

--select * from #my_emp_table

SELECT DISTINCT m.[EmployeeID], tbl.CNT,
  CASE WHEN CNT > 1 THEN 'incomplete' ELSE 'complete' END AS [Status]
  FROM #my_emp_table m
  JOIN (
      SELECT [EmployeeID], COUNT(distinct [status]) AS CNT FROM #my_emp_table GROUP BY [EmployeeID]
  ) tbl ON m.[EmployeeID] = tbl.[EmployeeID] 

答案 2 :(得分:0)

一种有点怪诞的方式

select 
employee_id, 'complete' as status
from your_table
group by employee_id
having avg(case when status='complete' then 1 else 0 end)=1