SQL查询中需要规范化

时间:2018-06-25 15:08:10

标签: sql sql-server sql-server-2008

我有一个称为学生数据的表,其中有20列

我必须像这样在每列上写条件

SELECT
    registered, Appeared, registered + Appeared AS col3 
FROM
    (SELECT 
     COUNT(REGDNO) AS registered, branch_code,
     SUM(CASE WHEN SUB1_GRADE <> 'Ab' AND SUB1_GRADE IS NOT NULL OR
                   SUB2_GRADE <> 'Ab' AND SUB1_GRADE IS NOT NULL OR
                   SUB2_GRADE <> 'Ab ' AND SUB2_GRADE IS NOT NULL OR
                   SUB3_GRADE <> 'Ab' AND SUB3_GRADE IS NOT NULL OR 
                   SUB4_GRADE <> 'Ab' AND SUB4_GRADE IS NOT NULL OR  
                   SUB5_GRADE <> 'Ab' AND SUB5_GRADE IS NOT NULL OR 
                   SUB6_GRADE <> 'Ab' AND SUB6_GRADE IS NOT NULL OR 
                   SUB7_GRADE <> 'Ab' AND SUB7_GRADE IS NOT NULL .........

有没有更简单的方法 请帮我

2 个答案:

答案 0 :(得分:1)

您可以使用unpivot将所有列变成一个坡度列,然后将条件应用于该列。

我不熟悉sql-server synthax(并且现在无法测试),但是在postgres中,例如:

  solr:
    image: solr
    container_name: solr    
    ports:
     - "9983:9983"
     - "8983:8983"
    networks:
      - gsec 
    volumes:
      - data:/opt/solr/server/solr/mycores
    entrypoint:
      - docker-entrypoint.sh
      - solr
      - start
      - -c
      - -f

答案 1 :(得分:0)

使用unpivot检查是否填充了任何列,并且<>'Ab'。请注意,无论如何,<>'Ab'对于Null返回false:

create table rr (a char(2), b char(2), c char(2), d char(2), e char(2), f char(2))

insert into rr values (null,'aa',null,null,'ac','ab')

Select sum(iif(u.[cols]<>'AB', 1,0))
from rr s
unpivot
(
  [cols]
  for [vals] in (a, b, c, d, e, f)
) u;