【问题标题】:MS SQL formulating aggregation and time stamp queryMS SQL 公式化聚合和时间戳查询
【发布时间】:2014-04-01 12:01:16
【问题描述】:
时间戳计名称参数名称值 2014-02-18 18:58:00 1$SGP A 415.7806091308594 2014-02-18 18:58:00 1$SGP B 240.3373565673828 2014-02-18 18:58:01 2$SGP A 393.191162109375 2014-02-18 18:58:02 2$SGP B 50.10090637207031 2014-02-18 18:58:00 3$SGP A 3484841472 2014-02-18 18:05:01 1$SGP A 0 2014-02-18 17:58:01 1$SGP A 0 2014-02-18 17:58:01 2$SGP A 290 2014-02-18 17:58:01 2$SGP D 0 2014-02-18 17:58:01 3$SGP A 3061691904 2014-02-18 17:57:01 3$SGP A 0 2014-02-18 17:57:02 3$SGP B 0

找出两个连续时间戳的时间戳差异,以及针对特定参数的每个单独仪表的值差异。

预期输出:18:58

01:00 1$SGP 415.7806091308594-0 01:00 2$SGP 393.191162109375-290 01:00 3$SGP 3484841472-3061691904

在 18:58 时,参数 A 的 1$SGP、2$SGP 和 3$SGP 抛出值。 在 17:58,参数 A 的 1$SGP、2$SGP 和 3$SGP 抛出值。 休息要么所有仪表不一起出现时间戳,如 18:05 时间戳中的秒数可以忽略。 所以,

01:00 1$SGP 415.7806091308594-0 01:00 2$SGP 393.191162109375-290 01:00 3$SGP 3484841472-3061691904

在 MS SQL 中提出查询时面临问题。我也不熟悉用于忽略在 mysql 中可以处理 date_format() 的第二个转换方法。

【问题讨论】:

    标签: java sql-server mssql-jdbc


    【解决方案1】:

    这是示例表:

    create table #t(ts datetime, mn char(5), pn char, val decimal (25,15));
    
    insert #t values 
    ('2014-02-18 18:58:00',      '1$SGP',           'A',          415.7806091308594),
    ('2014-02-18 18:58:00',      '1$SGP',           'B',          240.3373565673828),
    ('2014-02-18 18:58:01',      '2$SGP',           'A',          393.191162109375),
    ('2014-02-18 18:58:02',      '2$SGP',           'B',           50.10090637207031),
    ('2014-02-18 18:58:00',      '3$SGP',           'A',          3484841472),
    ('2014-02-18 18:05:01',      '1$SGP',           'A',          0),
    ('2014-02-18 17:58:01',      '1$SGP',           'A',          0),
    ('2014-02-18 17:58:01',      '2$SGP',           'A',          290),
    ('2014-02-18 17:58:01',      '2$SGP',           'D',          0),
    ('2014-02-18 17:58:01',      '3$SGP',           'A',          3061691904),
    ('2014-02-18 17:57:01',      '3$SGP',           'A',          0),
    ('2014-02-18 17:57:02',      '3$SGP',           'B',          0);
    

    这是查询:

    ;with t as (
        select cast(ts as smalldatetime) as ts, mn, pn, val from #t
    )
    ,
    tt as (
        select ts from t
        group by ts
        having count(*) >= 3
    ),
    ttt as (
        select *, row_number() over(partition by mn, pn order by ts desc) as rn
        from t where t.ts in (select tt.ts from tt)
    )
    select t1.ts, t1.mn, t1.val, t2.val
    from ttt t1
    inner join ttt t2 on t1.mn = t2.mn and t1.pn = t2.pn and t1.rn = 1 and t2.rn = 2;
    

    【讨论】:

    • 如果此答案对您有用,请接受/点赞,以便其他人从中受益。
    猜你喜欢
    • 2021-12-05
    • 2013-05-08
    • 2015-12-09
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多