如何在SQL中将5分钟的时间戳间隔转换为1分钟的间隔,同时保留其他信息?

时间:2019-02-05 23:25:24

标签: sql sql-server timestamp resolution intervals

我看到一个或两个主题在询问相反的问题(将1min时间戳转换为5min或其他时间戳间隔)。但是我完全不知道对此进行编程的想法。

这是我的输入表:

timestamp     Food      Beverage
15:00:00      Pizza      Coke
15:05:00      Burger     Coke
15:10:00      Hotdog     Pepsi
   …             …        …

这将是我想要的输出:

timestamp   Food    Beverage
 15:00:00   Pizza   Coke
 15:01:00   Pizza   Coke
 15:02:00   Pizza   Coke
 15:03:00   Pizza   Coke
 15:04:00   Pizza   Coke
 15:05:00   Burger  Coke
 15:06:00   Burger  Coke
 15:07:00   Burger  Coke
 15:08:00   Burger  Coke
 15:09:00   Burger  Coke
 15:10:00   Hotdog  Pepsi
 15:11:00   Hotdog  Pepsi
    …         …       …

谢谢!

2 个答案:

答案 0 :(得分:3)

最简单的方法是使用start = input("Would you like to encrypt(1) or decrypt(2) your password?: ") if start == "encrypt" or "1": print("Enter the password you want to encrypt: ") elif start == "decrypt" or "2": print("Enter the password you want to decrypt: ")

cross join

您也可以使用明确的select dateadd(minute, v.m, timestamp) as timestamp, food, beverage from t cross join (values (0), (1), (2), (3), (4)) v(m); / select来做到这一点:

union all

答案 1 :(得分:0)

您可以使用 DATEADD 。参数输入 N 表示分钟。

ROW_NUMBER 将增加每行的时间戳。

DECLARE @interval varchar(10) = 5

DROP TABLE IF EXISTS #data

SELECT timestamp='15:00:00',Food='Pizza',Beverage='Coke'
INTO #data
UNION ALL SELECT timestamp='15:05:00',Food='Burger',Beverage='Coke'
UNION ALL SELECT timestamp='15:10:00',Food='Pizza',Beverage='Pepsi'

DROP TABLE IF EXISTS #TAB 
CREATE TABLE #TAB (id int)

EXEC ('INSERT INTO #TAB
SELECT TOP '+@interval+ ' ROW_NUMBER() OVER(ORDER BY name) FROM sys.columns')

SELECT timestamp=CAST(DATEADD(n,ROW_NUMBER() OVER (PARTITION BY timestamp,food,beverage ORDER BY Food),timestamp) as time) , Food,Beverage
FROM #data
CROSS JOIN #TAB
ORDER BY 1

输出将是:

+------------------+--------+----------+
|    timestamp     |  Food  | Beverage |
+------------------+--------+----------+
| 15:01:00.0000000 | Pizza  | Coke     |
| 15:02:00.0000000 | Pizza  | Coke     |
| 15:03:00.0000000 | Pizza  | Coke     |
| 15:04:00.0000000 | Pizza  | Coke     |
| 15:05:00.0000000 | Pizza  | Coke     |
| 15:06:00.0000000 | Burger | Coke     |
| 15:07:00.0000000 | Burger | Coke     |
| 15:08:00.0000000 | Burger | Coke     |
| 15:09:00.0000000 | Burger | Coke     |
| 15:10:00.0000000 | Burger | Coke     |
| 15:11:00.0000000 | Pizza  | Pepsi    |
| 15:12:00.0000000 | Pizza  | Pepsi    |
| 15:13:00.0000000 | Pizza  | Pepsi    |
| 15:14:00.0000000 | Pizza  | Pepsi    |
| 15:15:00.0000000 | Pizza  | Pepsi    |
+------------------+--------+----------+