SQL行计数选择-MS SQL

时间:2019-02-28 11:00:01

标签: sql sql-server

Day1    Day2    Day3    Day4    Day5    Day6    Day7    Day8    Day9    Day10   Day11   Day12   Day13   Day14   Day15   Day16   Day17   Day18   Day19   Day20   Day21   Day22   Day23   Day24   
A   A   A   A   A   A   WO  B   B   B   B   B   B   WO  C   C   C   C   C   C   WO  A   A   A   

我有类似上述格式的数据。我需要选择在同一行中有多少个“ A”。

A,B,C表示换档时间 WO-一周之内

第1天,第2天...可能与每个月不同。

3 个答案:

答案 0 :(得分:2)

您可以使用巨型CASE表达式,也可以使用APPLY

SELECT t.*, t1.A_cnt
FROM table t CROSS APPLY
     ( SELECT COUNT(*) AS A_cnt
       FROM ( VALUES ([DAY1]), ([DAY2]), . .  ) tt(col)
       WHERE t.col = 'A'
     ) t1;

案例expression的版本为:

SELECT t.*,
       (CASE WHEN [day1] = 'A' THEN 1 ELSE 0 END) +
       (CASE WHEN [day2] = 'A' THEN 1 ELSE 0 END) +
       . . .   
FROM table t;

如果只需要COUNT则可以:

SELECT COUNT(*) AS A_cnt
FROM table t CROSS APPLY
     ( VALUES ([DAY1]), ([DAY2]), . .  )
     ) t1(col)
WHERE t1.col = 'A';

答案 1 :(得分:1)

您也可以尝试使用unpivot进行以下操作。

 select count(*) as 'ACount' from 
    (
        select u.x,u.y
        from youtable s 
        unpivot 
        ( 
            [y] 
            for [x] in (Day1,Day2,Day3,Day4...) 
        ) u
    ) t where t.y='A'

如果要使其动态,可以尝试如下操作。

create table test_1(day1 varchar(10),day2 varchar(10),day3 varchar(10))

insert into test_1 select 'a','b','a'
--Generate Columns Dynamically
declare  @colsUnpivot nvarchar(max)
  = stuff((select ','+quotename(C.name)
           FROM sys.columns c
           WHERE c.object_id = OBJECT_ID('dbo.test_1') 
           for xml path('')), 1, 1, '')
--Form the dynamic query
declare @query nvarchar(max)=' select count(*) as ACount from 
    (
        select u.x,u.y
        from test_1 s 
        unpivot 
        ( 
            [y] 
            for [x] in (' + @colsUnpivot + ')' +
        ') u' +
    ') t where t.y=''A'''
--Finally execute it
exec sp_executesql @query

答案 2 :(得分:1)

使用像这样的不可透视运算符:

declare @tmp table
(
    Day1 char(1),
    Day2 char(2)
)

insert into @tmp
(
   Day1,
   Day2
)
VALUES
(
   'A', -- Day1 - char(1)
   'A'  -- Day2 - char(2)
)


select count(1)
from (
    select * from @tmp
) a
UNPIVOT
(
    d FOR Days IN (Day1, Day2)  
) unpvt
where d = 'A'