2

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

  1. 如果 date<20120401 然后依靠 id >>>> 给出结果
  2. 如果 date>20120401 然后依靠 id >>>> 给出结果

如果 idnumber xyz 有 20 项日期<20120401 和 30 项日期>20120401

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

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

但是如何打印身份证号码?

4

4 回答 4

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
于 2013-02-15T15:36:28.500 回答
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
于 2013-02-15T15:39:41.603 回答
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
于 2013-02-15T15:36:20.337 回答
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

有更经济有效的方法来获得预期的结果,但这是最容易理解的。

于 2013-02-15T15:36:25.113 回答