选择日期时间差(以分钟为单位)小于特定分钟数

时间:2015-02-02 06:11:05

标签: sql sql-server

我有这样的查询:

SELECT DATEDIFF(minute,t.Paydate,t.DelDate) as Mtime 
       FROM Transaction_tbl t WHERE Locid=6 

这将返回如下结果:

Mtime
8
2
10
20
15
7
6

但是,在那个查询中,我必须给出条件,就像我想要显示结果一样只有不到10分钟或不到15分钟。 我还有一个位置的表格。在那里,我有一个 timeinterval 列,数据类型时间(0)。实际上这个值我想在同一个查询中传递。 那么如何重写我的查询显示结果不到10分钟呢?

2 个答案:

答案 0 :(得分:4)

AND子句中添加WHERE条件:

SELECT  
    DATEDIFF(MINUTE, t.Paydate, t.DelDate) AS Mtime 
FROM Transaction_tbl t 
WHERE 
    Locid = 6
    AND DATEDIFF(MINUTE,t.Paydate,t.DelDate) < 10

根据您的新疑点:

SELECT  
    DATEDIFF(MINUTE, t.Paydate, t.DelDate) AS Mtime,
    COUNT(*) AS Count 
FROM Transaction_tbl t 
WHERE 
    Locid = 6
GROUP BY Mtime
HAVING DATEDIFF(MINUTE, t.Paydate, t.DelDate) < 10

你可以做这样的事情

SELECT  
   case when ( DATEDIFF(MINUTE, t.Paydate, t.DelDate)<10) then DATEDIFF(MINUTE, t.Paydate, t.DelDate) else null end AS lessthan10,
case when ( DATEDIFF(MINUTE, t.Paydate, t.DelDate)>10) then DATEDIFF(MINUTE, t.Paydate, t.DelDate) else null end AS greaterthan10,
    COUNT(*) AS Count 
FROM Transaction_tbl t 
WHERE 
    Locid = 6
GROUP BY Mtime
HAVING DATEDIFF(MINUTE, t.Paydate, t.DelDate) < 10

答案 1 :(得分:0)

试试这个。

WITH CTE(Mtime) As (
select DATEDIFF(minute,t.Paydate,t.DelDate) as Mtime 
from Transaction_tbl  t
)
Select Mtime from 
CTE
Where Mtime < 10

参考:Using Common Table Expressions