如何计算表格行中的列值?

时间:2015-03-25 12:13:58

标签: sql-server

在SQL Server中,我有一个表,其中有15列,这些列包含数据SLPLCL8,{{ 1}}那样。

4

如上所述我的表就在那里,现在我想计算每个empid的PL或CL或SL,请帮帮我。

2 个答案:

答案 0 :(得分:1)

在一行中跨列聚合的需求是一个很好的指标,表明您存储错误的数据。我会将其更改为以下内容:

empid  D_number  val
sam    1         PL
sam    2         8
sam    3         PL

在这种情况下,您可以只进行计数或条件求和。例如,一次性得到PL和SL的条件和:

select empid, sum(case when val = 'PL' then 1 else 0 end),
    sum(case when val = 'SL' then 1 else 0 end)
from myTable
group by empid

或者,如果您只对PL计数感兴趣,可以COUNT

select empid, count(*)
from myTable
where val = 'PL'
group by empid

但是,假设您无法对表架构做任何事情,那么您有两种选择:

  1. 明确地对每一列进行条件求和(男孩会快速变得丑陋):

    select empid, 
        case when d1 = 'PL' then 1 else 0 end + 
            case when d2 = 'PL' then 1 else 0 end +
            case when d3 = 'PL' then 1 else 0 end +
            ...,
        case when d1 = 'SL' then 1 else 0 end + 
            case when d2 = 'SL' then 1 else 0 end +
            case when d3 = 'SL' then 1 else 0 end +
            ...
    from myTable
    
  2. UNPIVOT数据使其看起来像上面的表格,然后使用条件总和:

    with cte as (
        select empid, D_number, val
        from (
            select empid, d1, d2, d3, d4, d5, ...
            from myTable
        ) x
        unpivot (val for D_number in
            (d1, d2, d3, d4, d5, ...)
        )
    )
    select empid, sum(case when val = 'PL' then 1 else 0 end),
        sum(case when val = 'SL' then 1 else 0 end)
    from cte
    group by empid
    

答案 1 :(得分:1)

使用UNPIVOT

测试数据和表格:

DECLARE @t table
(empid varchar(10), D1 char(2), D2 char(2), D3 char(2), D4 char(2),D5 char(2),
 D6 char(2),D7 char(2), D8 char(2), D9 char(2),D10 char(2), D11 char(2),
 D12 char(2), D13 char(2), D14 char(2), D15 char(2))
INSERT @t values
('sam', 'PL','8','PL','4','8','SL','8','SL','4','CL','8','CL','8','8','8'),
('sunny','8','CL','4','CL','SL','8','4','SL','4','PL','8','8','8','8','8'),
('zimmy','4','4','4','8','8','8','4','4','8','8','8','8','8','8','8')

查询:

SELECT empid, value, count(*) count
FROM @t as p  
UNPIVOT      
(value FOR col IN           
([D1],[D2],[D3],[D4],[D5],[D6],[D7],[D8],[D9],
 [D10],[D11],[D12],[D13],[D14],[D15]) ) AS unpvt  
WHERE value in ('PL','CL','SL')
GROUP BY empid, value

结果:

empid   value  count
sam     CL     2
sam     PL     2
sam     SL     2
sunny   CL     2
sunny   PL     1
sunny   SL     2