SQL查询 - 以更简单的方式重写

时间:2018-05-24 15:07:20

标签: sql sql-server

使用SQL Server 2016

我有以下T-SQL查询,它可以满足我的需求,但它包含大量重复内容。有没有办法以更优雅的方式重写它?

import numpy as np

x = np.arange(10)
y = np.array([100, 101, 102, 103, 104, 105, 106, 107])
z = {'X': x, 'Y': y}
np.save('./data.npy', z)
z1 = np.load('./data.npy')
print(type(z1))
print(z1)
print(z1['X']) #this line will generate an error

正如你所看到的,我正在使用相同的声明,日期转换为一个月12次。 请指教。 问候。

3 个答案:

答案 0 :(得分:3)

测试脚本很难,但是您可以尝试以下方法:

SELECT z.*
FROM
(
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY [id], DATEADD(MONTH,-1 * t.num, @date) ORDER BY [action_timestamp] DESC) AS rowNum,
           [new_state] AS [Last_State],
           DATEADD(MONTH, t.num, @date) AS [date]
    FROM [dbo].[CR_hist_Data]
    CROSS JOIN (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)  )  t(num)
    WHERE [action_timestamp_formatted] < DATEADD(MONTH, -1 * t.num, @date)
) z
WHERE z.rowNum = 1

答案 1 :(得分:0)

使用CASE:

SELECT z.*
FROM
(
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY [id], MONTH([action_timestamp] ORDER BY [action_timestamp] DESC) AS rowNum,
           [new_state] AS [Last_State],
           CASE WHEN [action_timestamp_formatted] < DATEADD(MONTH, 1, @date) THEN DATEADD(MONTH, 0, @date)
                WHEN [action_timestamp_formatted] < DATEADD(MONTH, 2, @date) THEN DATEADD(MONTH, 1, @date)
                WHEN [action_timestamp_formatted] < DATEADD(MONTH, 3, @date) THEN DATEADD(MONTH, 2, @date) END AS [date]
    FROM [dbo].[CR_hist_Data]
) z
WHERE z.rowNum = 1

答案 2 :(得分:0)

我认为使用公用表表达式可能有所帮助。

with dates(r, currmonth, lastmonth) as
(select 1 r, eomonth(@date) CurrMonth, eomonth(@date,-1) LastMonth
 union all
 select r+1, eomonth(@date,-1*r), eomonth(@date,-1*(r+1)) from dates
 where r < 12)

SELECT z.*
FROM
(
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY [id],dates.r ORDER BY [action_timestamp] DESC) AS rowNum,
           [new_state] AS [Last_State],
           dates.currmonth AS [date]
    FROM [dbo].[CR_hist_Data]
    join dates on 1=1
    WHERE [action_timestamp_formatted] < dates.lastmonth
) z
WHERE z.rowNum = 1