SQL查询在上次更改列的值时从表中获取行详细信息

时间:2011-01-03 19:59:43

标签: sql sql-server tsql

我有两张桌子。

表1

   Item
    1
    2

表2

   Item   Date    Amount
    1     12/31     30
    1     12/30     30
    1     12/29     20
    2     12/31     100
    2     12/30     90
    2     12/29     90

现在我的结果应该

   Item   Date    Amount
    1    12/29     20
    2    12/30     90 
    3    12/31     12

基本上,我试图找出最近价格变化的日期。反过来,我将使用此信息来计算项目当前价格的天数。

由于

2 个答案:

答案 0 :(得分:1)

;WITH cte
     AS (SELECT *,
                Row_number() OVER (PARTITION BY Item ORDER BY Date) -
                Row_number() OVER (PARTITION BY Amount, Amount ORDER BY Date) AS
                grp
         FROM   table2)
SELECT Item,
       MAX(Amount) AS Amount,
       MIN(Date)   AS startrange,
       MAX(Date)   AS endrange,
       1+DATEDIFF(DAY,MIN(Date),MAX(Date)) AS numdays
FROM   cte
GROUP  BY grp,
          Item  

返回测试数据的以下内容

Item        Amount      startrange endrange   numdays
----------- ----------- ---------- ---------- -----------
1           20          2010-12-29 2010-12-29 1
1           30          2010-12-30 2010-12-31 2
2           90          2010-12-29 2010-12-30 2
2           100         2010-12-31 2010-12-31 1

答案 1 :(得分:0)

试试这个:

SELECT Item, Date, Amount
FROM
(
    SELECT
        T2.Item,
        T2.Date,
        T2.Amount,
        ROW_NUMBER() OVER (PARTITION BY T2.Item ORDER BY T2.Date DESC) rn
    FROM table2 T2
    JOIN
    (
        SELECT Item, Amount
        FROM
        (
            SELECT
                Item,
                Amount,
                ROW_NUMBER() OVER (PARTITION BY Item ORDER BY Date DESC) rn
            FROM table2
        ) T1
        WHERE rn = 1
    ) T3
    ON T2.Item = T3.Item AND T2.Amount <> T3.Amount
) T4
WHERE rn = 1

示例数据的结果:

Item  Date        Amount
1     2010-12-29  20    
2     2010-12-30  90    

<强>解释

子查询T3使用ROW_NUMBER查找每个项目的最新价格。然后将其连接回原始表格,并删除项目价格等于最近价格的行。然后,再次使用ROW_NUMBER技术为每个项目找到剩余数据的最新价格。这是第二个最近的价格。