0

我正在尝试对一组特定的数据进行日常分析。该表如下所示:

custNo  visitTime          FirstVisit

1234    2013-01-31 20:15  
1234    2013-01-31 22:30
1234    2013-02-15 02:30
1234    2013-02-15 06:30
1234    2013-02-15 11:30
1234    2013-02-15 21:30

我正在尝试Daily analysis使用custNo. 正如您在上面看到的,客户编号重复出现。一天是2013-01-31 1:00am2013-02-01 00:59am。我正在尝试对FirstVistTime. 所以对于31st Jan,它应该是2013-01-31 20:15,对于15th Feb它应该是2013-02-15 02:30

到目前为止,我想出了这个查询:

select custNo, visitTime, FirstVisit=(select MIN(c.visitTime) FROM customer c  where
(c.custNo=ct.custNo and c.visitTime >= '01/01/2013 01:00' and c.visitTime < '03/01/2013 
01:00') 
from customer ct 
where visitTime >= '01/01/2013 01:00' 
    and visitTime < '03/01/2013 01:00' 

这样做的问题是 - 如果custNo重复它会考虑所有行并计算最小日期,在上述情况下将是 2013-01-31 20:15. 我尝试使用min(visitTime)over(partition by custNo,visitTime). 那么它是一个subquery返回两个值的。

4

3 回答 3

1

尝试这个:

select custNo, min(visitTime) from customer 
group by custNo, CAST(visitTime AS date)
order by custNo

或者:

select t1.custNo, t1.visitTime, t2.minVal 
from customer t1 left join 
(
  select custno, min(visitTime) as minVal  from customer 
  group by custno, CAST(visitTime AS date)      
) t2 on t1.custNo = t2.custNo and CAST(t2.minVal as date) = CAST(t1.visitTime as date)
order by t1.custNo
于 2013-08-20T14:12:05.223 回答
0

实际上,您应该能够按客户和日期分组,并为每个客户和日期选择最短访问时间:

SELECT custNo, MIN(visitTime)
FROM customer c
GROUP BY custNo, CONVERT(DATE, visitTime, 112)
ORDER BY custNo, MIN(visitTime)
于 2013-08-20T14:04:14.243 回答
0

这是你要找的吗?

SELECT custno, min(visit)
FROM visitors
GROUP BY custno, CONVERT(DATE, VISIT)
ORDER BY custno, min(visit)

这是一个SQLFiddle

于 2013-08-20T14:04:22.193 回答