[英]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.我有一个如下结构的查询,它检查给定列中的任何条目是否不是 null,如果找到匹配项(非空值),则立即返回 Y,如果所有值都是 null,则返回 N。它适用于名为 first_name 的列,但我需要使其也适用于其他列,即 last_name、middle_name,最好全部在一个查询中以节省执行时间。 Y or N must be returned for each of the columns specified.
必须为每个指定的列返回 Y 或 N。
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).我有另一个查询,它是一种替代方法并且做同样的工作(1/0 而不是 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 column_name IS NULL THEN 0 ELSE 1 END)> 0 THEN 'Y' ELSE AS_N' END)你想检查。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.