简体   繁体   English

WHERE 在 SELECT 子查询上

[英]WHERE on a SELECT sub-query

Here is a table这是一张桌子

--------------------
|   Id    |   Val  |
|---------|--------|
|   1     |   4    |
|   2     |   3    |
|   3     |   5    |
|   4     |   1    |
--------------------

I need a query like我需要一个查询

SELECT * , 
CASE 
 WHEN val > 3 THEN 'PASS' 
 ELSE 'FAIL' 
END as Status
FROM StatusTable
WHERE Status = 'PASS'

But, it doesn't seem to work that way.但是,它似乎并没有那样工作。 here is the error:这是错误:

Uncaught Error: near "when": syntax error

Please help me with a workaround.请帮我解决问题。

Assuming this is oracle: There are 2 things that break this query.假设这是 oracle:有两件事破坏了这个查询。

  • It's possible to do SELECT * to get all columns, but not to do SELECT *, <some other column> .可以执行SELECT *来获取所有列,但不能执行SELECT *, <some other column> That will raise an ORA-00923: FROM keyword not found where expected.这将引发 ORA-00923: FROM keyword not found where expected。 The workaround is to alias the table and the "*" like this SELECT t.*, t.<some other column>解决方法是为表格和“*”添加别名,例如SELECT t.*, t.<some other column>
  • In the WHERE clause table columns or functions can be referenced, not aliases of columns that are in the SELECT clause.WHERE子句中可以引用表列或函数,而不是SELECT子句中列的别名。 The WHERE Status = 'PASS' fails because "Status" is an alias, not a column. WHERE Status = 'PASS'失败,因为“Status”是别名,而不是列。

Taking both those into account, the query becomes:考虑到这两个因素,查询变为:

WITH StatusTable(id, val) AS
(
SELECT 1,4 FROM DUAL UNION ALL
SELECT 2,3 FROM DUAL UNION ALL
SELECT 3,5 FROM DUAL UNION ALL
SELECT 4,1 FROM DUAL 
) 
SELECT 
  t.* , 
  CASE 
   WHEN t.val > 3 THEN 'PASS' 
   ELSE 'FAIL' 
  END as Status
FROM StatusTable t
WHERE
  CASE 
   WHEN t.val > 3 THEN 'PASS' 
   ELSE 'FAIL' 
  END = 'PASS';

I am not answering directly your question but seems you want all line where val > 3我没有直接回答你的问题,但你似乎想要 val > 3 的所有行
Why do you need to use 'Fail' and 'Pass'?为什么需要使用“失败”和“通过”?

SELECT Id, Val
FROM StatusTable
WHERE Val > 3

should give you the same result as with other suggested query应该给你与其他建议查询相同的结果

If you need a column with 'Pass', you can add it manually:如果您需要带有“通过”的列,您可以手动添加它:

SELECT Id, Val, 'Pass'
FROM StatusTable
WHERE Val > 3

You are missing from clause in your query您在查询中缺少 from 子句

SELECT * , 
CASE 
 WHEN val > 3 THEN 'PASS' 
 ELSE 'FAIL' 
END as Status
FROM Table_Name
WHERE Status = 'PASS'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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