2017-04-26 69 views
0

這背後的邏輯是如果Ser_request數字對於同一位置是相同的,那麼請考慮具有最大「停機前功率」的行。需要被更新的行是列名ID與最小值如何更新其他列中相同的值?

我需要創建三個新列調開始日期,調結束日期,可調節直流電源,並從repective列插入數據

  • downtime_start =調開始時間

    -downtime_end =調結束日期

    -power_before_downtime =調DC電源

我試過這樣做,但通過分組的值是相同的,我無法找到第一行。

我使用的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 | 3/8/2017 6:41:59 PM | 0003 | 0 | 0 | 0

+0

你使用MySQL或MS SQL Server? (不要標記不涉及的產品。) – jarlh

+1

我無法閱讀那些圖片的小文本。 (這裏的大多數人想格式化文本,而不是圖像...) – jarlh

+0

我正在使用MS SQL 2010 –

回答

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

+0

我收到一個錯誤,因爲所有三列的inavlid列名 –

+0

@Looking_for_answers我編輯了我的查詢並添加了五個缺失的列。如果出現錯誤,請提供完整的錯誤信息 –

相關問題