oracle 如何选择ID号为偶数的列?

qv7cva1a  于 2023-06-05  发布在  Oracle
关注(0)|答案(9)|浏览(326)

我试图解决Hackerrank问题Weather Observation Station 3,如下所述:

我提出了以下解决方案:

SELECT CITY
FROM STATION
WHERE MOD(ID, 2) = 0

但是当我试着运行它时,我得到编译器消息“错误答案”。我看不出这个查询有什么问题?

inkz8wg9

inkz8wg91#

SELECT DISTINCT CITY
FROM STATION
WHERE MOD(ID, 2) = 0
f1tvaqid

f1tvaqid2#

你可以试试这个查询:

SELECT DISTINCT CITY FROM STATION WHERE (ID % 2) = 0
bvjxkvbb

bvjxkvbb3#

对于DB2:

SELECT DISTINCT CITY 
FROM STATION
WHERE MOD(ID, 2) = 0;

对于Oracle:

SELECT DISTINCT CITY 
FROM STATION
WHERE MOD(ID, 2) = 0;

MySQL:

SELECT DISTINCT CITY 
FROM STATION
WHERE MOD(ID, 2) = 0;

或者...

SELECT DISTINCT CITY 
FROM STATION
WHERE ID%2=0;

对于MSSQL:

SELECT DISTINCT CITY 
FROM STATION
WHERE ID%2=0;
0sgqnhkj

0sgqnhkj4#

SELECT DISTINCT CITY FROM STATION WHERE (ID % 2) = 0;
  • DISTINCT用于不允许重复,
  • (Id % 2)告诉SQL将Id除以2并返回余数。
  • 由于我们只查找偶数值,因此将其设置为= 0,如2%2=04%2=0等。
  • 如果我们在寻找奇数的Id s,我们会使用= 1,因为当奇数除以2时,总是有1的余数。
i34xakig

i34xakig5#

MYSQL:

SELECT DISTINCT CITY FROM STATION WHERE (ID % 2)=0;

ORACLE:

SELECT DISTINCT CITY FROM STATION WHERE MOD(ID, 2)=0;
rvpgvaaj

rvpgvaaj6#

如果问题类似于“从仅具有偶数ID号的车站查询城市名称列表”,则答案为

select CITY from station where ID % 2 = 0;

但由于进一步的标准,如“但必须排除重复从你的答案。”你的答案应该是

select DISTINCT CITY from station where ID % 2 = 0;
m2xkgtsf

m2xkgtsf7#

我建议另一个解决方案:

SELECT DISTINCT CITY
    FROM STATION
    WHERE ID LIKE '%0' OR ID LIKE '%2' OR ID LIKE '%4' OR ID LIKE '%6' OR ID LIKE '%8';
e5nszbig

e5nszbig8#

在MSSQL中:

SELECT CITY
FROM STATION
WHERE (ID % 2) = 0
GROUP BY CITY
xn1cxnb4

xn1cxnb49#

SQL Server使用带有case-when语句的子查询:-

SELECT DISTINCT CITY FROM STATION WHERE ID IN (SELECT 
                                               CASE
                                                   WHEN ABS(ID%2) = 0 THEN ID
                                               END 
                                               FROM STATION);

相关问题