【问题标题】:Populating missing rows using SELECT statement使用 SELECT 语句填充缺失的行
【发布时间】:2023-02-02 19:54:29
【问题描述】:

我在编写 SELECT SQL 语句时遇到以下问题,想知道是否有人可以提供帮助。我有下表,其中包含 ProductID 和 Status 字段:

ProductID Status
AP56546
AP56546 Shipped
AP56546
AD92402 Delayed
AD92402
AD92402
BE91455
BE91455
SL19423
SL19423
SL19423
SL19423 Expected

如果其中一个具有针对它的状态,我如何填充具有相同 ID 的所有产品的状态?如果某个产品不存在状态,则它可以保持为空。如何使用 SELECT 语句执行此操作?预期结果应低于(ProductID BE91455 仍然为空,因为它出现的任何行都没有状态)

ProductID Status
AP56546 Shipped
AP56546 Shipped
AP56546 Shipped
AD92402 Delayed
AD92402 Delayed
AD92402 Delayed
BE91455
BE91455
SL19423 Expected
SL19423 Expected
SL19423 Expected
SL19423 Expected

谢谢

【问题讨论】:

  • 使用窗口MAX

标签: sql sql-server


【解决方案1】:

您可以使用以下查询获得所需的结果:

样品表

CREATE TABLE TableData (
    ProductID varchar(10),
    Status varchar(10)
)

样本数据

INSERT INTO TableData (ProductID, Status)
VALUES
    ('AP56546', ''),
    ('AP56546', 'Shipped'),
    ('AP56546', ''),
    ('AD92402', 'Delayed'),
    ('AD92402', ''),
    ('AD92402', ''),
    ('BE91455', ''),
    ('BE91455', ''),
    ('SL19423', ''),
    ('SL19423', ''),
    ('SL19423', ''),
    ('SL19423', 'Expected');
    

询问

WITH CTE AS (
 SELECT ProductID, Status 
  FROM TableData
  WHERE Isnull(Status,'') <> ''
  GROUP BY ProductID, Status
)
SELECT TableData.ProductID, COALESCE(CTE.Status, '') AS Status
FROM TableData
LEFT JOIN CTE
ON TableData.ProductID = CTE.ProductID;

【讨论】:

    【解决方案2】:

    以下使用由 ProductId 分区的 max 应该适合您:

    select ProductId, Max(Status) over(partition by ProductId) Status
    from t;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多