按编号选择计数列组

时间:2015-06-22 15:29:03

标签: sql sql-server

Emp_No        Emp_Shift       Emp_Date    
500            AL              1/5/2015
600            S               2/5/2015
600            H               3/5/2015
500            S               4/5/2015
500            AL              5/5/2015
600            AL              6/5/2015

我在这个问题上需要帮助,如何在3列中返回计数>> EX:

Emp_No    Count Al    Count S    Count H
500         2            1           0
600         1            1           1

3 个答案:

答案 0 :(得分:0)

你可以试试这个: -

SELECT EMP_NO, COUNT(CASE
                     WHEN Emp_Shift = 'AL' THEN 1 ELSE 0 END AS COUNT_AL
                     WHEN Emp_Shift = 'S' THEN 1 ELSE 0 END AS COUNT_S
                     WHEN Emp_Shift = 'H' THEN 1 ELSE 0 END AS COUNT_H)
FROM YOUR_TABLE
GROUP BY EMP_NO;

答案 1 :(得分:0)

这会奏效。你必须为每个条件提供单独的案例陈述 SQLFIDDLE用于相同的SQLFIDDLE

    SELECT EMP_NO, 
           sum(CASE WHEN Emp_Shift = 'AL' THEN 1 ELSE 0 END) AS COUNT_AL,
           sum(CASE  WHEN Emp_Shift = 'S' THEN 1 ELSE 0 END) AS COUNT_S,
           sum(CASE  WHEN Emp_Shift = 'H' THEN 1 ELSE 0 END) AS COUNT_H
FROM YOUR_TABLE
GROUP BY EMP_NO;

答案 2 :(得分:0)

使用Pivot:

declare @YOUR_TABLE TABLE 
    ([Emp_No] int, [Emp_Shift] varchar(2), [Emp_Date] datetime)
;

INSERT INTO @YOUR_TABLE
    ([Emp_No], [Emp_Shift], [Emp_Date])
VALUES
    (500, 'AL', '2015-01-05 00:00:00'),
    (600, 'S', '2015-02-05 00:00:00'),
    (600, 'H', '2015-03-05 00:00:00'),
    (500, 'S', '2015-04-05 00:00:00'),
    (500, 'AL', '2015-05-05 00:00:00'),
    (600, 'AL', '2015-06-05 00:00:00')
;
select Emp_No,[AL] AS [Count Al],[S] As [Count S],[H] AS [Count H] from (
select Emp_No,[Emp_Shift],[Emp_Date] from @YOUR_TABLE)T
PIVOT(COUNT(Emp_Date) FOR Emp_Shift IN ([AL],[S],[H]))P

在Dynamic Query中使用Pivot:

if object_id('tempdb..#t') is not null
    drop table #t

CREATE  TABLE #t
    ([Emp_No] int, [Emp_Shift] varchar(2), [Emp_Date] datetime)
;

INSERT INTO #t
    ([Emp_No], [Emp_Shift], [Emp_Date])
VALUES
    (500, 'AL', '2015-01-05 00:00:00'),
    (600, 'S', '2015-02-05 00:00:00'),
    (600, 'H', '2015-03-05 00:00:00'),
    (500, 'S', '2015-04-05 00:00:00'),
    (500, 'AL', '2015-05-05 00:00:00'),
    (600, 'AL', '2015-06-05 00:00:00')
;

DECLARE @statement NVARCHAR(max)
,@columns NVARCHAR(max)

SELECT @columns = ISNULL(@columns + ', ', '') + N'[' + tbl.Emp_Shift + ']'
FROM (
   SELECT DISTINCT [Emp_Shift]
   FROM #t
   ) AS tbl

SELECT @statement = ' select Emp_No,[AL] AS [Count Al],[S] As [Count S],[H] AS [Count H] from (
select Emp_No,[Emp_Shift],[Emp_Date] from #t)T
PIVOT(COUNT(Emp_Date) FOR Emp_Shift IN  (' + @columns + ')) as pvt'

EXEC sp_executesql @statement = @statement