我的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
week
和units
列中的值会重复我不想要的值。应删除重复记录。我希望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
我考虑过从原始表构建一个查询表来创建最后一个表,但我不知道如何。非常感谢任何帮助。
答案 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()
,以便为每个Week
和Units
组合选择最早的日期,但我发现我们需要排除在[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)
您可以使用select
和into
。像下面这样的东西可以帮助你:
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
查询来确保它返回您真正想要的结果。此外,列名称中的空格经常会让我失望,因此请确保方括号和单引号也正确。