这背后的逻辑是如果同一位置的Ser_request数相同,那么考虑具有Max“停电前功率”的行。需要更新的行是列名称ID ,其最小值为
我需要创建三个新列Adj Start date,Adj end date,Adj DC power并插入来自各列的数据
downtime_start =调整开始日期
-downtime_end =调整结束日期
-power_before_downtime =调整直流电源
我试过这样做但是通过分组相同的值我无法找到第一行。
我正在使用sql server 2012
这是我到目前为止所尝试的:
select location,downtime_start , count(*)
from dbo.TB1
group by location,downtime_start , count(*)
having count(*)>1
在此查询之后我得到了TB1的结果,我不知道如何对它们进行分组并将值插入到各自的列中。
感谢任何帮助
谢谢
ID | location | downtime_start | downtime_end | power_before_downtime | power_after_downtime | creation_time | end_time | ser_request
1 | xyz.a | 3/8/2017 2:00:00 PM | 3/10/2017 8:00:00 AM | 14.16 | 13.67 | 3/8/2017 3:25:37 PM | 3/8/2017 6:41:59 PM | 0003
2 | xyz.a | 3/8/2017 2:00:00 PM | 3/10/2017 8:00:00 AM | 14.16 | 13.67 | 3/8/2017 3:25:37 PM | 3/8/2017 6:41:59 PM | 0003
3 | xyz.a | 3/8/2017 2:00:00 PM | 3/10/2017 8:00:00 AM | 14.16 | 13.67 | 3/8/2017 3:25:37 PM | 3/8/2017 6:41:59 PM | 0003
输出表应该是:
ID | location | downtime_start | downtime_end | power_before_downtime| power_after_downtime| creation_time | end_time
|ser_request | Adj Start date | Adj end date | Adj DC power
1 | xyz.a | 3/8/2017 2:00:00 PM | 3/10/2017 8:00:00 AM | 14.16 | 13.67 |3/8/2017 3:25:37 PM | 3/8/2017 6:41:59 PM| 0003 | 3/8/2017 2:00:00 PM | 3/10/2017 8:00:00 AM | 14.16
2 | xyz.a | 3/8/2017 2:00:00 PM | 3/10/2017 8:00:00 AM | 14.16
| 13.67 | 3/8/2017 3:25:37 PM | 3/8/2017 6:41:59 PM | 0003
| 0 | 0 | 0
3 | xyz.a | 3/8/2017 2:00:00 PM| 3/10/2017 8:00:00 AM | 14.16
| 13.67 3/8/2017 3:25:37 PM | 2017年3月8日下午6:41:59 | 0003 | 0 | 0 | 0
答案 0 :(得分:1)
UPDATE T
SET
[Adj Start date] = downtime_start,
[Adj end date] = downtime_end,
[Adj DC power] = power_before_downtime
FROM (
SELECT [Adj Start date], [Adj end date], [Adj DC power], downtime_start, downtime_end, power_before_downtime,
rn = ROW_NUMBER() OVER (PARTITION BY downtime_start, downtime_end ORDER BY id)
FROM dbo.TB1
) T
WHERE rn = 1
如果您需要选择数据,请使用CASE WHEN rn = 1 THEN downtime_start ELSE 0 END