从SQL Server中的另一个表创建顺序表

时间:2014-02-26 13:57:15

标签: sql sql-server

我的SQL Server数据库中有以下表格:

Product      Week       Units      Exta units effective     Extra units
A515      2014-01-11      51          2014-01-25              23.24
A515      2014-01-11      51          2014-01-11              25.86
A515      2014-01-18      52          2014-01-25              23.24
A515      2014-01-18      52          2014-01-11              25.86
A515      2014-01-25      50          2014-01-25              23.24
A515      2014-01-25      50          2014-01-11              25.86
A515      2014-02-01      45          2014-01-25              23.24
A515      2014-02-01      45          2014-01-11              25.86

weekunits列中的值会重复我不想要的值。应删除重复记录。我希望extra units effective列从与week列对应的最早日期开始。基本上我想要一张上表中的表格,如下所示,

Product       Week    Units      Exta units effective      Extra units
A515       2014-01-11   51          2014-01-11                25.86
A515       2014-01-18   52          2014-01-11                25.86
A515       2014-01-25   50          2014-01-25                23.24
A515       2014-02-01   45          2014-01-25                23.24

我考虑过从原始表构建一个查询表来创建最后一个表,但我不知道如何。非常感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

使用ROW_NUMBER只是稍微复杂一点,CTE似乎是有序的:

;With Ordered as (
    SELECT *,ROW_NUMBER() OVER (PARTITION BY Week,Units
                                ORDER BY
                CASE WHEN [Exta units effective] >= Week THEN 0
                     ELSE 1 END,
                [Exta units effective]) as rn
    FROM [Unknown Table]
)
select * from Ordered where rn = 1

通常这只是ORDER BY表达式中的ROW_NUMBER(),以便为每个WeekUnits组合选择最早的日期,但我发现我们需要排除在[Exta units effective]值之前的任何Week,因此我添加了CASE表达式来过滤那些到行编号末尾的表达式。

答案 1 :(得分:0)

您可以使用row_number()执行此操作,select product, week, units, extraunitseffective, extraunits from (select t.*, row_number() over (partition by product, week order by extraunitseffective) as seqnum from table t ) t where seqnum = 1; 在按所需日期排序的每个组中分配一个顺序值。然后选择第一个:

{{1}}

答案 2 :(得分:0)

您可以使用selectinto。像下面这样的东西可以帮助你:

SELECT 
max(Product) as Product,
Week,
Units,
min([Extra units effective]) as 'Extra units effective',
max([Extra units]) as 'Extra units'
INTO Some_Other_Table
FROM Original_Table
GROUP BY Week, Units

您可能需要稍微使用select查询来确保它返回您真正想要的结果。此外,列名称中的空格经常会让我失望,因此请确保方括号和单引号也正确。