2011-11-11 88 views
18

我今天在查詢工作這需要我用下面找到所有奇數ID值查找偶數或奇數的ID值

(ID % 2) <> 0 

誰能告訴我這是什麼做的?它的工作,這是偉大的,但我想知道爲什麼。

+0

(ID%2)= 0用於選擇偶數 – anandharshan

回答

31

ID % 2正在檢查餘數是多少,如果您將ID除以2.如果您將一個偶數除以2,它將始終有餘數爲0.其他任何數字(奇數)都將導致非零值。這是什麼檢查。

+0

太棒了。這正是我需要的。謝謝! – Phoenix

2

它將ID除以2並檢查餘數是否爲零;這意味着,這是一個奇怪的ID。

7

爲了找到偶數我們應該用

select num from table where (num % 2) = 0 
-1

在Oracle中,

select num from table where MOD (num, 2) = 0; 
0

股息%除數

股息是數字表達式來劃分。股息必須是sql server中的整數數據類型的任何表達式。

除數是分紅的數字表達式。除數在sql server中除數必須是整型數據類型的表達式。

SELECT 15 % 2 

Output 
1 

紅利= 15

除數= 2

比方說,你想查詢

查詢城市名稱的列表,從站只有偶數ID號。

架構結構STATION:

ID Number 

CITY varchar 

STATE varchar 


select CITY from STATION as st where st.id % 2 = 0 

Will fetch the even set of records 


In order to fetch the odd records with Id as odd number. 

select CITY from STATION as st where st.id % 2 <> 0 

%功能降低值,以0或1

+0

這個問題正在尋找*解釋*,而不僅僅是其他代碼示例。您的回答對提問者沒有任何洞察力,並且可能會被刪除。請[編輯] *解釋*比較如何選擇奇數。 –

-1

<>表示不相等。然而,在SQL的某些版本中,你可以寫!=

0
for even: 
select * from tablename where columname/2 not like '%.%'; 
for eg: 
select sal from emp where sal/2 not like '%.%'; 
for odd; 
select * from tablename where columname/2 like '%.%'; 
select sal from emp where sal/2 like '%.%'; 
+1

這並不回答這個問題,即使這樣做,也沒有代碼的上下文或解釋。僅有代碼的回覆通常不會有幫助。 – WillardSolutions