SQL-对变量进行分组并选择重复组的第一组的最后一行

时间:2014-09-17 13:29:49

标签: sql sql-server-2008

所以我有这个问题。假设我已经对变量进行了分组,我试图选择第一组重复的组。

表1

ProductID   Name                              Dates
----------- ---------------------------------- ---------- 
491         Paint - Silver                     1999/08/1          
491         Paint - Silver                     1999/12/23         
491         Paint - Blue                       2000/1/1         
491         Paint - Silver                     2001/1/1       
491         Paint - Red                        2001/1/21          
491         Paint - Red                        2001/1/25         
491         Paint - Silver                     2002/3/4         
491         Paint - Blue                       2003/4/14          
491         Paint - Blue                       2003/4/15         
491         Paint - Blue                       2004/3/26         
491         Paint - Red                        2005/2/1         
491         Paint - Red                        2005/5/1         
491         Paint - Yellow                     2006/7/2         
491         Paint - Yellow                     2009/1/1        
491         Paint - Black                      2010/1/1        
491         Paint - Black                      2011/1/3

问题是,我想在它变为Paint - Blue之前选择Paint - Silver,因此对于Paint - Silver,日期将是1999/12/23。简而言之,我想要将第一个产品的最后日期更改为productID = 491的另一个产品。这仅适用于一个productID(即491)。我想对多个都具有相似格式的productID执行此操作。似乎没有任何作用,任何帮助都将受到赞赏

2 个答案:

答案 0 :(得分:1)

这是您应该指出产品名称更改的查询。

SELECT a.name, b.name, a.dates, b.dates , (a.row - b.row) as row_diff
FROM 
(SELECT *, @rowa := @rowa + 1 AS row FROM product 
        CROSS JOIN (SELECT @rowa := 0) AS r) a 
LEFT JOIN 
(SELECT *, @rowb := @rowb + 1 AS row FROM product 
        CROSS JOIN (SELECT @rowb := 0) AS r) b 
ON a.dates < b.dates 
WHERE a.name != b.name AND (a.row - b.row) = -1;

这将给出以下结果集:

+--------------+--------------+------------+------------+----------+
| name         | name         | dates      | dates      | row_diff |
+--------------+--------------+------------+------------+----------+
| Paint-Silver | Paint-Blue   | 1999-12-23 | 2000-01-01 |       -1 |
| Paint-Blue   | Paint-Silver | 2000-01-01 | 2001-01-01 |       -1 |
| Paint-Silver | Paint-Red    | 2001-01-01 | 2001-01-21 |       -1 |
| Paint-Red    | Paint-Silver | 2001-01-25 | 2002-03-04 |       -1 |
| Paint-Silver | Paint-Blue   | 2002-03-04 | 2003-04-14 |       -1 |
| Paint-Blue   | Paint-Red    | 2004-03-26 | 2005-02-01 |       -1 |
| Paint-Red    | Paint-Yellow | 2005-05-01 | 2006-07-02 |       -1 |
| Paint-Yellow | Paint-Black  | 2009-01-01 | 2010-01-01 |       -1 |
+--------------+--------------+------------+------------+----------+

答案 1 :(得分:0)

我不熟悉sql,但是你无法遍历名单,将每行与下面的行进行比较,并寻找对不同名称(或指定名称,例如油漆蓝)的更改)然后在发现差异时选择当前行?