我有一个名为list的表,我必须提取以下内容。 字段是id和日期
如果有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?
答案 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