SQL显示特定列

时间:2016-03-30 16:49:44

标签: sql oracle

我应该如何编写仅以“YES”显示内部列值的查询?

Hospital_ID  MATERINITY  ENT  DERMATOLOGY  ORTHOPEDICS  
          1  YES         NO   NO           NO   
          2  YES         YES  NO           NO   
          3  YES         YES  NO           YES   

我正在寻找的结果是Hospital_ID“3”:

Hospital_ID  MATERINITY  ENT  ORTHOPEDICS  
          3  YES         YES  YES   

不会显示值为“NO”的列。

3 个答案:

答案 0 :(得分:0)

尝试

SELECT * 
FROM TableName 
WHERE MATERINITY = "YES" AND 
      DERMATOLOGY = "YES" AND 
      ORTHOPEDICS = "YES"

答案 1 :(得分:0)

好吧,如果您只是想在排除皮肤科专栏时将其排除在外,并且您不关心任何其他列是否为NO(除非它们都是NO),那么它将是:

SELECT Hospital_ID, MATERNITY, ENT, ORTHOPEDICS,
FROM DepartmentTable
WHERE DERMATOLOGY = 'NO' AND (MATERNITY = 'YES' OR ENT = 'YES' OR ORTHOPEDICS = 'YES');

这只会给你DERMATOLOGY为NO的行,但是有另一列的值为'YES'。我假设您不希望所有列都为“否”的结果。

答案 2 :(得分:0)

您在尝试删除列时会遇到麻烦,尤其是当您包含多家医院时。我建议将yes表示为带有联合查询的行,然后您可以在报表中交叉表。

SELECT Hospital_ID, 'MATERNITY' Dept FROM myTable t WHERE t.MATERNITY='YES'
UNION SELECT Hospital_ID, 'ENT' Dept FROM myTable t WHERE t.ENT='YES'
UNION SELECT Hospital_ID, 'DERMATOLOGY' Dept FROM myTable t WHERE t.DERMATOLOGY='YES'
UNION SELECT Hospital_ID, 'ORTHOPEDICS' Dept FROM myTable t WHERE t.ORTHOPEDICS='YES'

如果您需要过滤医院id = 3,请执行以下操作:

SELECT Hospital_ID, Dept FROM (
SELECT Hospital_ID, 'MATERNITY' Dept FROM myTable t WHERE t.MATERNITY='YES'
UNION SELECT Hospital_ID, 'ENT' Dept FROM myTable t WHERE t.ENT='YES'
UNION SELECT Hospital_ID, 'DERMATOLOGY' Dept FROM myTable t WHERE t.DERMATOLOGY='YES'
UNION SELECT Hospital_ID, 'ORTHOPEDICS' Dept FROM myTable t WHERE t.ORTHOPEDICS='YES') x
WHERE Hospital_ID=3