我是SQL查询的新手,我遇到一种情况,我不知道如何解决。 我有两个表,如:
null
我尝试过的是这个
Table B
Id AId Timestamp (datetimeoffset(7) column)
1 1 2017-08-31 08:25:32.7000000 -07:00
2 2 2017-08-31 10:25:32.5000000 -05:00
3 2 2017-08-31 10:25:32.9000000 -05:00
4 8 2017-08-31 10:25:32.5000000 -02:00
5 1 2017-05-30 18:31:43.8000000 +03:00
6 7 2017-05-29 18:31:43.8000000 +03:00
Table A
Id Name
1 AA
2 AB
7 AC
8 AD
但是我的问题是它应该加上偏移量,然后在分钟处四舍五入,并计算该分钟内至少有一条记录的表A中的行数,但是忽略了偏移量而只是四舍五入我认为这就是为什么它很糟糕的问题。
因此,对于日期select DATEADD(MINUTE, DATEDIFF(MINUTE, 0, p.Timestamp), 0) as TimestampMinute, count(1) Count
from A a
cross apply (select top 1 b.Timestamp from B b where a.Id=b.AId) p
group by DATEADD(MINUTE, DATEDIFF(MINUTE, 0, p.Timestampl), 0)
order by DATEADD(MINUTE, DATEDIFF(MINUTE, 0, p.Timestampl), 0)
,我应该从表A中获得2行(ID 1和2)。表A的ID 1对应于表B的第1行,而ID 2对应于表2和3的行(应用不同)。
预期结果:
2017-08-31 15:25
我正在尝试从错误中学习并提高自己,所以请保持温柔。
答案 0 :(得分:0)
您需要先将datetimeoffset
转换为datetime2
,然后舍入到分钟,因此代码如下:
convert(datetime2, b.timestamp, 1) -- timestamp is your column from table b
第三个参数( 1 用于解决时区差异并进行计算。如果为 0 ,它将省略该部分并使用{{1}进行转换}。
解决方案:
+00.00
输出:
select
DATEADD(MINUTE, DATEDIFF(MINUTE, 0, convert(datetime2, b.timestamp, 1)), 0) as TimestampMinute ,
count(distinct b.aid) as cnt
from b
inner join a on b.aid = a.id -- new part
group by DATEADD(MINUTE, DATEDIFF(MINUTE, 0, convert(datetime2, b.timestamp, 1)), 0)
order by DATEADD(MINUTE, DATEDIFF(MINUTE, 0, convert(datetime2, b.timestamp, 1)), 0);
答案 1 :(得分:0)
您需要的是类似下面的查询
; with newB as
(
select id,Aid,DATEADD(MINUTE, DATEDIFF(MINUTE, 0, Timestamp)- datepart(tz,Timestamp), 0) as TimestampMinute
from B
)
select TimestampMinute, count(distinct Aid) from A join newB B
on A.id=B.Aid
group by TimestampMinute