SQL:同一表中一列不同的输出行

SQL:同一表中一列不同的输出行,sql,sql-server,tsql,Sql,Sql Server,Tsql,我还没有找到用文字正确解释的方法,所以这里有一个例子: | Product number | Price Period | Price | ----------------------------------------- | 0001 | 1 | 200 | ----------------------------------------- | 0001 | 2 | 200 | ------------

我还没有找到用文字正确解释的方法,所以这里有一个例子:

| Product number | Price Period | Price |
-----------------------------------------
| 0001           | 1            | 200   |
-----------------------------------------
| 0001           | 2            | 200   |
-----------------------------------------
| 0002           | 1            | 110   |
-----------------------------------------
| 0002           | 2            | 115   |
-----------------------------------------
因此,同一表格中的同一产品有多个价格。主键由产品编号和价格周期组成

如果价格自上一期以来发生了变化,我如何分发产品?我现在唯一能想到的方法就是在子选择上进行内部连接。

您可以尝试使用lag函数


您也可以通过更简单的自连接来实现它。我假设这是一个模式:

CREATE TABLE Product
(ProductNumber int, PricePeriod int, Price int);

INSERT INTO Product
    (ProductNumber, PricePeriod, Price)
VALUES
    (1, 1, 200),
    (1, 2, 200),
    (2, 1, 110),
    (2, 2, 115);
查询应该是

select A.ProductNumber, A.PricePeriod, A.Price, B.PricePeriod, B.Price
FROM Product A
JOIN Product B
ON A.ProductNumber = B.ProductNumber
AND A.PricePeriod < B.PricePeriod
AND A.Price != B.Price;
在此查询中,有一个条件a.PricePeriod 如果价格自上一期以来发生了变化,我如何分发产品


您提出的查询有什么问题?请给出预期结果。您可以安全地删除和更改价格不是空的,但如果有多个价格周期,则此操作将失败。。。如果我理解正确,OP需要从一个周期到下一个周期进行更改。但这并不完全清楚。可能是查询总是被限制在一个周期内,而它的前身。。。如果周期是无间隔的,你可以使用A.PricePeriod=B.PricePeriod+1…也许你是对的,但这两种方式都不清楚。
select po.Product from products po inner join
    (
    select pr.product,pr.Period,pr.Price from products pr inner join
        (
        select product,max(period)as [period] from products
        group by product
        ) mx on mx.Product = pr.Product and mx.period = pr.Period
    ) mxx on mxx.Product = po.Product 
and po.Period = mxx.Period-1
and mxx.Price <> po.Price 
CREATE TABLE Product
(ProductNumber int, PricePeriod int, Price int);

INSERT INTO Product
    (ProductNumber, PricePeriod, Price)
VALUES
    (1, 1, 200),
    (1, 2, 200),
    (2, 1, 110),
    (2, 2, 115);
select A.ProductNumber, A.PricePeriod, A.Price, B.PricePeriod, B.Price
FROM Product A
JOIN Product B
ON A.ProductNumber = B.ProductNumber
AND A.PricePeriod < B.PricePeriod
AND A.Price != B.Price;
CREATE TABLE T
    ([Product number] varchar(20), [Price Period] int, [Price] int);

INSERT INTO T
    ([Product number], [Price Period], [Price])
VALUES
    ('0001', 1, 100),
    ('0001', 2, 200),
    ('0001', 3, 200),
    ('0002', 1, 110),
    ('0002', 2, 115);

SELECT [Product number],
       [Price Period],
       [Price]
FROM
(
SELECT [Product number],
       [Price Period],
       [Price],
       [Price] - LAG([Price])OVER(PARTITION BY [Product number] ORDER BY [Product number]) Changes,
       (SELECT MAX([Price period]) FROM T WHERE [Product number] = TT.[Product number]) N
FROM T TT
) TBL
WHERE Changes > 0
      AND
      [Price Period] = N;