简体   繁体   中英

How to make this sql query work for multiple columns

I have a query structured like below, it checks if any of the entry in a given column is not null, if it finds a match (a value that is not null) it immediately returns Y, if all values are null it returns N. It works with a column called first_name but I need to make it work for other columns as well ie last_name, middle_name, preferably all in a single query to save execution time. Y or N must be returned for each of the columns specified.

SELECT CASE
  WHEN EXISTS(SELECT *
  FROM (patient AS p JOIN patient_score AS s ON p.patient_id=s.patient_id)
  WHERE first_name IS NOT NULL) 
  THEN 'Y'
  ELSE 'N'
  END AS your_result 

I have another query which is an alternative and does the same job (1/0 instead of Y/N). But I don't know how to make it work with multiple columns either. A procedure that could work by supplying multiple column names would work as well.

SELECT COUNT(*) AS fn FROM 
  (SELECT 1 
    FROM (patient AS p JOIN patient_score AS s ON p.patient_id=s.patient_id) 
    WHERE first_name IS NOT NULL
    LIMIT 1) AS T;

I think it is the query that you want, you have to add a SELECT element (CASE WHEN SUM(CASE WHEN column_name IS NULL THEN 0 ELSE 1 END) > 0 THEN 'Y' ELSE 'N' END AS column_name) for each column you want to check.

SELECT 
    CASE WHEN SUM(CASE WHEN first_name IS NULL THEN 0 ELSE 1 END) > 0 THEN 'Y' ELSE 'N' END AS first_name

FROM patient AS p
INNER JOIN patient_score AS s ON p.patient_id = s.patient_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM