简体   繁体   English

对于SQL Server中使用游标的每个循环

[英]For Each Loop in SQL Server using Cursor

I have a table with 4 cols. 我有一张桌子有4列。 HouseNo, Date, Time and Temp. 门牌号,日期,时间和温度

I have managed to obtain the different HouseNos in a separate table. 我设法在单独的表格中获得了不同的房屋编号。 Now i want to insert all the dates for all the house nos. 现在我想为所有房屋编号插入所有日期。


Sample Data from table. 表中的样本数据。 There are like a few million rows like this. 像这样的几百万行。

HouseNo Date Time Temp
102 1/1/2010 10:00 67
102 2/1/2010 10:00 73
102 3/1/2010 10:00 75
103 1/1/2010 10:00 69
103 2/1/2010 10:00 63
104 1/1/2010 10:00 71
104 2/1/2010 10:00 12

Expected Output is 预期输出为

table 1 表格1

102 1/1/2010 
102 2/1/2010 
102 3/1/2010

table 2 表2

103 1/1/2010 
103 2/1/2010

table 3 表3

104 1/1/2010 
104 2/1/2010

Then i want to be able to loop through each row in the tables derieved to perform some operation on the temperature field. 然后,我希望能够遍历表中的每一行,以对温度场执行一些操作。

If you have one ON/OFF pair per day and the OFF is always before the ON, this gets you the duration. 如果您每天有一对ON / OFF,并且OFF总是在ON之前,则可以得到持续时间。

SELECT 
HouseNo,  
Date, 
DATEDIFF(s,
   MIN(CASE WHEN Relay='OFF' THEN Time ELSE NULL END),
   MIN(CASE WHEN Relay='ON' THEN Time ELSE NULL END)
) As OffDuration
FROM YourTable
GROUP BY HouseNo,  Date

But any normal real life dataset will have multiple ON/OFF pairs. 但是任何正常的现实生活数据集都将具有多个ON / OFF对。 Can you give more detail? 您能提供更多细节吗?

something like this ? 这样的事情?

    CREATE TABLE new_table
    AS (SELECT * FROM old_table);

you can also put some WHERE part and SELECT 您还可以放置一些WHERE部分并选择

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM