多个选择在一个表上

时间:2013-02-15 15:27:40

标签: mysql

我有一个名为list的表,我必须提取以下内容。 字段是id和日期

  1. 如果日期< 20120401,则依靠id>>>>给结果
  2. 如果日期> 20120401,则依靠id>>>>给结果
  3. 如果有20项日期< 20120401和30项日期> 20120401的idnumber xyz

    那么结果应该是......

    xyz 20 30

    我做得像......

    select 
     (select count(id) from list where id='xyz' and date<20120401) as date1,
     (select count(id) from list where id='xyz' and date>20120401) as date2;
    

    结果是20 30

    但是如何打印idnumber?

4 个答案:

答案 0 :(得分:2)

SELECT
id,
SUM(CASE WHEN date < 20120401 THEN 1 ELSE 0 END) AS date1,
SUM(CASE WHEN date > 20120401 THEN 1 ELSE 0 END) AS date2,
FROM list
WHERE id = 'xyz'
GROUP BY id

更新:

SELECT
list.id,
idmaster.idlocation,
SUM(CASE WHEN list.date < 20120401 THEN 1 ELSE 0 END) AS date1,
SUM(CASE WHEN list.date > 20120401 THEN 1 ELSE 0 END) AS date2,
FROM list
INNER JOIN idmaster ON list.id = idmaster.idnumber
WHERE list.id = 'xyz'
GROUP BY id

答案 1 :(得分:0)

尝试

select id, count(id) from list where id='xyz' and date < 20120401
union
select id, count(id) from list where id='xyz' and date > 20120401

答案 2 :(得分:0)

您正在寻找GROUP BY条款,可能是这样的:

SELECT
    l2.id,
    (SELECT COUNT(id)
    FROM list l1
    WHERE l1.id = l2.id AND date < 20120401) AS date1,
    (SELECT COUNT(id)
    FROM list l1
    WHERE l1.id = l2.id AND date > 20120401) AS date2
FROM
    list l2
GROUP BY
    l2.id

有更多具有成本效益的方法可以获得理想的结果,但这是最容易理解的。

答案 3 :(得分:0)

试试这个:

 SELECT
    id,
    SUM(CASE WHEN date < 20120401 
    THEN 1 ELSE 0 END) AS date1,
    SUM(CASE WHEN date > 20120401 
    THEN 1 ELSE 0 END) AS date2,
    FROM list
    WHERE id = 'xyz'
    GROUP BY id