如何在单个查询中获得不同列中的奇数ID?

时间:2014-11-21 09:28:17

标签: mysql sql

例如我有一个如下所示的表格..我希望在偶数/奇数ids的基础上有单独的列

-----------------------------------------------------
| ID  |  Names
-----------------------------------------------------
| 1   |  Name1
-----------------------------------------------------
| 2   |  Name2
-----------------------------------------------------
| 3   |  Name3
-----------------------------------------------------
| 4   |  Name4
-----------------------------------------------------

我想设计一个可以给我的查询

-------------------
| Even  |  Odd    |
-------------------
| Name2 |  Name1  |
-------------------
| Name4 |  Name3  |
-------------------

6 个答案:

答案 0 :(得分:6)

select 
  max(case id%2 when 1 then name end) as odd,
  max(case id%2 when 0 then name end) as even
from your_table
group by floor((id+1)/2)

SQL Fiddle Demo

答案 1 :(得分:1)

如果您想变得奇怪或偶数,请使用下一个查询: 选择奇数记录:

SELECT * FROM table WHERE ID % 2 = 1

选择,即使是

SELECT * FROM table WHERE ID % 2 = 0

如果你想装饰成两列,请尝试下一个解决方案:

SELECT
    odd.name as Odd,
    (SELECT name FROM table WHERE ID = odd.ID + 1 ) as Even
FROM
    table as odd
WHERE
    odd.ID % 2 = 1

答案 2 :(得分:1)

如果您的Id列包含序号而数字之间没有任何差距,则:

SELECT t1.name as ODD,
       t2.name as EVEN
FROM   YourTable t1
       left outer JOIN YourTable t2
         ON t1.Id + 1 = t2.Id
where t1.Id%2 = 0

注意:如果数字之间存在差距,则ODD中的某些内容将显示为NULL,或者如果差距超过3,则可能会跳过name

答案 3 :(得分:0)

使用模运算符%。找到奇偶校验(偶数或奇数的属性)。

...其中id%2等于0;

这将为您提供结果中的偶数。

不等于0的是奇数id。

答案 4 :(得分:0)

上述结果集可以通过以下代码实现 -

SELECT Even, Odd   
FROM (SELECT *, ROW_NUMBER()OVER(ORDER BY Even) AS ROW   
    FROM (SELECT CASE WHEN ID % 2 = 0 THEN Names ELSE NULL END AS 'Even'  
    FROM TableName)TAB1  
    WHERE Even IS NOT NULL)T1  
FULL OUTER JOIN   
(SELECT *, ROW_NUMBER()OVER(ORDER BY Odd) AS ROW  FROM  
    (SELECT CASE WHEN ID % 2 = 1 THEN Names ELSE NULL END AS 'Odd'  
    FROM TableName) TAB2  
    WHERE Odd IS NOT NULL) T2  
ON T1.ROW=T2.ROW  

答案 5 :(得分:0)

如果您的ID是顺序的,那么

SELECT tb1.ODD, tb2.EVEN
FROM
(
    SELECT Id, name ODD
    FROM YourTable
    where (`Id` % 2) = 1
 ) AS tb1 

 JOIN 

 (SELECT Id, name EVEN
  FROM  YourTable
  WHERE (`Id` % 2) = 0
 ) AS tb2 

ON (tb1.Id + 1 = tb2.Id)

WHERE tb1.ODD IS NOT NULL
ORDER BY tb1.Id