Using Row_number() OVER(partition BY..) along with declaring local variables

岁酱吖の 提交于 2019-12-12 06:07:23

问题


I have a sql query, in this sql query I want to select distinct columns irrespective of column first. For other sql query I use Row_number() OVER(partition BY..) and I also need to use inner join. The query in which I want to use row_number and inner join is -

DECLARE @columns NVARCHAR(MAX)

DECLARE @params NVARCHAR(MAX) = '@columns NVARCHAR(MAX) OUTPUT'

DECLARE @sql NVARCHAR(MAX) = 'SELECT @columns = STUFF(
(
    SELECT '',''+ [column_name] FROM information_schema.columns
    WHERE (table_schema = ''dbo''
          AND table_name = ''main_mps_dqs_analog'') 
          AND (ordinal_position <= 73) FOR XML PATH('''')),1,1,'''')'

EXEC sp_executesql @sql, @params, @columns OUTPUT

SET @sql = 'SELECT '+ @columns + ' FROM dbo.main_mps_dqs_analog WHERE logtime BETWEEN ''2014-10-10 07:17:00'' AND ''2014-10-10 08:47:00''' 

EXEC(@sql)

I want to apply inner join of this table with INDUS2_BDS.dbo.ddtable and I want beam_current and logtime of this INDUS2 database table and how to apply partition BY beam_current in this query.


回答1:


SET @sql = 'SELECT ' + @columns + ' ,AnotherTable.beam_current, RowNumber() Over(Partition By SomeColumn Order By SomeColumn) AS Rn
 FROM dbo.TableName join AnotherTable on TableName.SomeColumn = AnotherTable.SomeColumn
WHERE logtime BETWEEN ''2014-10-10 07:17:00'' AND ''2014-10-10 08:47:00'''

I solved it by this sql query with the help from Giorgi



来源:https://stackoverflow.com/questions/29094100/using-row-number-overpartition-by-along-with-declaring-local-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!