在SQL上对部分表数据进行分组

时间:2016-07-28 14:03:05

标签: sql

我有一个表格数据如下。在这种情况下,员工可以拥有1或0或(1和0),但永远不会存在多个1和多个0组合的员工。

员工 状态



<table>
	<tr>
		<th> Employee</th>
		<th> Status </th>
   <tr>
  <tr>
		<td>abc </td>
		<td> 1</td>
  </tr>
    <tr>
		<td>abc </td>
		<td> 1</td>
  </tr>
    <tr>
		<td>PQR </td>
		<td> 1</td>
  </tr>
    <tr>
		<td>XYZ </td>
		<td> 0</td>
  </tr>
</table>
&#13;
&#13;
&#13;

以下是输出的预期结果。

&#13;
&#13;
<table>
	<tr>
		<th> Employee</th>
		<th> Status </th>
   <tr>
    <tr>
		<td>abc </td>
		<td> $</td>
  </tr>
    <tr>
		<td>PQR </td>
		<td> yes</td>
  </tr>
    <tr>
		<td>XYZ </td>
		<td> no</td>
  </tr>
</table>
&#13;
&#13;
&#13;

这意味着,如果有重复记录,则状态应为$,如果为1,则为是,如果为0则为否。

提前感谢您提供帮助

我尝试过:

;with CTEE (RowNumber, EmployeeName, [Status]) As 
(select a.RowNumber,
        a.EmployeeName, 
        case when a.rowNumber > 1 then '' 
             when a.rowNumber = 1 and Working = 0 then 'N' 
             else 'Y' end as [Status] 
 from (select Row_Number() over(Partition by EmployeeName order by EmployeeName) as [RowNumber],
       EmployeeName, 
       [Status] 
       from [Table] 
       group by EmployeeName, [Status] ) a ) 

select EmployeeName, [Status] 
from CTEE c1 
where (RowNumber = 1 
and EmployeeName not in 
       (select EmployeeName 
        from CTEE where EmployeeName = c1.EmployeeName and [Status] = '')) or RowNumber =2

1 个答案:

答案 0 :(得分:0)

有很多方法,这里有一个使用派生表来获取COUNT()

SELECT T.Employee,
       CASE WHEN Cnt > 1 THEN '$'
            WHEN Cnt = 1 AND Status = 1 THEN 'yes'
            ELSE 'no' END as 'Status'

FROM        (SELECT DISTINCT Employee, Status
             FROM Table) T
INNER JOIN  (SELECT COUNT(STATUS) as 'Cnt', Employee
             FROM Table
             GROUP BY Employee) T2 on T2.Employee = T.Employee