根据WHERE子句的结果返回列值

时间:2014-09-24 14:49:19

标签: sql

我想根据WHERE子句选择记录,并在结果中包含一个列,告诉每个记录为何传递WHERE子句的过滤器。

这样的东西
SELECT name, location, networth, reason
FROM aTable
WHERE location = "France" OR networth > "100"

可能会返回

name|location|networth|reason --reason is the part I need help with
-----------------------------
Joe |France  |0       |Location
Jeff|England |500     |Net worth
Tim |France  |500     |Net worth and location

是否有一种更简洁的方法来设置“reason”而不是在SELECT子句中重复WHERE子句的谓词?

2 个答案:

答案 0 :(得分:3)

我会用连锁条件来做这件事。随着您添加更多内容,它会变得更加容易。而且,在大多数数据库中,我会使用子查询。使用concat()结合原因:

select a.*
from (select a.*,
             concat((case when location = 'France' then 'France; ' else '' end),
                    (case when network > 100 then 'net worth; ' else '' end)
                   ) as reasons
      from atable a
     ) a
where reasons <> '';

此查询有各种细微差别,具体取决于您的数据库(例如字符串连接可能不同)。但是这允许您只定义一次原因,而不必在where子句和case语句中重复它们。

答案 1 :(得分:1)

唯一的方法是使用SELECT子句中的CASE语句重复WHERE子句中的条件。

SELECT NAME,
    location,
    networth,
    CASE 
        WHEN location = "France"
            AND networth > "100"
            THEN "Location and Net Worth"
        WHEN location = "France"
            THEN "Location"
        WHEN networth > "100"
            THEN "Net Worth"
        END AS reason
FROM aTable
WHERE location = "France"
    OR networth > "100"