SQL坚持这个

时间:2013-06-03 09:42:52

标签: sql db2

我需要从表中选择只有一行存在该ID的行。

示例表,有两列 ID优先和时间戳 所以第一行是ID 1,时间戳01/01/2013

ID      Timestamp
1       01/01/2013
2       02/02/2013
3       04/02/2013
3       07/02/2013
4       20/03/2013

所以,对于这个表,我只想返回ID为1,2,4的记录,因为这些记录只有1行。

然后我需要只返回这些行,如果它们的时间戳超过一个月前。时间戳采用此格式2012-11-12-22.00.15.541231

有人可以帮忙吗?

5 个答案:

答案 0 :(得分:3)

这应该适合你:

SELECT *
FROM mytable
WHERE id NOT IN (
    SELECT id
    FROM mytable
    GROUP BY id
    HAVING COUNT(*) > 1
) AND time_created < current_timestamp - 1 month

答案 1 :(得分:0)

您可以对此输出使用group by子句 -

修改

在datestamp列

上添加Condition
SELECT *
  FROM Your_Table_Name
 WHERE Id IN
       (SELECT Id FROM Your_Table_Name GROUP BY Id HAVING COUNT(*) = 1)
 AND time_created < current_timestamp - 1 month

答案 2 :(得分:0)

这样的事情应该有效。

select id
from yourtable
where timestampfield <= current timestamp - 1 month
group by id
having count(*) = 1

减去1个月的部分来自here

答案 3 :(得分:0)

SQL Fiddle

MySQL 5.5.30架构设置

CREATE TABLE Table1
    (`ID` int, `Timestamp` date)
;

INSERT INTO Table1
    (`ID`, `Timestamp`)
VALUES
    (1, '2013-01-01'),
    (2, '2013-02-02'),
    (3, '2013-04-02'),
    (3, '2013-07-02'),
    (4, '2013-03-20')
;

查询1

select ID,Timestamp
from Table1
where DATEDIFF(curdate(),DATE_SUB(Timestamp,INTERVAL 1 MONTH))>=1
group by ID
having count(ID)=1

<强> Results

| ID |                       TIMESTAMP |
----------------------------------------
|  1 |  January, 01 2013 00:00:00+0000 |
|  2 | February, 02 2013 00:00:00+0000 |
|  4 |    March, 20 2013 00:00:00+0000 |

答案 4 :(得分:0)

如果您只需要返回ID和时间戳,则可以避免使用子查询,如下所示:

SELECT ID, MAX(Timestamp) AS Timestamp
FROM atable
GROUP BY ID
HAVING COUNT(*) = 1
   AND MAX(Timestamp) < CURRENT TIMESTAMP - 1 MONTH
;