选择具有相似行的所有记录满足条件的行

时间:2015-07-16 21:03:30

标签: sql-server

我有一张包含许多记录的表,但是例如..

ID | USER ID | DATE
1  | 1       | 2014-05-26
2  | 1       | 2015-05-08
3  | 2       | 2014-05-20

我正在尝试为日期超过6个月的记录选择USER_ID,但如果有另一条具有相同USER_ID且不符合该条件的记录,则不要包含它们。 例如,我想只返回用户ID为2的记录。

我的问题是我能做到

SELECT USER_ID FROM TABLE WHERE DATEDIFF(month, DATE, GETDATE()) > 6

但仍会返回USER_ID 1的记录。我确信这非常容易,但我无法在此方面取得进展。

4 个答案:

答案 0 :(得分:2)

您可以使用以下查询:

SELECT USER_ID
FROM mytable
GROUP BY USER_ID
HAVING COUNT(CASE WHEN DATEDIFF(month, [DATE], GETDATE()) <= 6 THEN 1 END) = 0

上述内容将排除{em}至少有一个行的USER_ID行,DATE66个月。< / p>

Demo here

如果要选择所有字段,则可以使用窗口版本的条件COUNT,如:

SELECT *
FROM (
  SELECT *, 
         COUNT(CASE WHEN DATEDIFF(month, [DATE], GETDATE()) <= 6 THEN 1 END) 
         OVER (PARTITION BY USER_ID) AS cnt       
  FROM mytable ) t
WHERE cnt = 0

Demo here

或者使用NOT EXISTS

SELECT *
FROM mytable AS t1
WHERE NOT EXISTS (SELECT 1
                  FROM mytable AS t2
                  WHERE t1.USER_ID = t2.USER_ID 
                        AND DATEDIFF(month, t2.[DATE], GETDATE()) <= 6)

Demo here

答案 1 :(得分:1)

喜欢这个吗?

<p>ABC</p>

<script>
  alert("I am in the HTML script tag.");
  headLoad.doSomething("123"); // should alert

  // The following will NOT execute because the "else" clause of the
  // "if(!headLoad)" will not be executed until just prior to the </body>.
  // the global doSomething() function is currently undefined.
  doSomething("456");   // will NOT work, nor should it.
</script>

<p>XYZ</p>

答案 2 :(得分:1)

请接受你的陈述并带走另一个:

    WITH UsersWithYoungerDates AS
    (
        SELECT USER_ID
        FROM TABLE
        WHERE DATEDIFF(month, DATE, GETDATE()) <= 6 
    )
    SELECT USER_ID 
    FROM TABLE 
    WHERE DATEDIFF(month, DATE, GETDATE()) > 6
    AND USER_ID NOT IN(SELECT USER_ID FROM UsersWithYoungerDates)

答案 3 :(得分:1)

async.parallel([
  function(callback){
    setTimeout(function(){
        callback(null, 'one');
    }, 200);
  },
  function(callback){
    setTimeout(function(){
        callback(null, 'two');
    }, 100);
  }
],
// optional callback
function(err, results){
    // the results array will equal ['one','two'] even though
    // the second function had a shorter timeout.
});

请注意,这将过滤 7个月或更长时间,而不是&#34;超过6个月&#34;。 DATEDIFF向下舍入。您可能希望重新设计原始计划的这一方面。

你也可能知道这一点,但SELECT USER_ID FROM [TABLE] WHERE DATEDIFF(month, DATE, GETDATE()) > 6 and USER_ID not in ( select USER_ID from [TABLE] where 6 <= datediff(month, date, getdate()) ); 是一个保留字,所以如果它不仅仅是一个(误导:P)占位符,它还需要标识符分隔符。