在SQL Server中将多行值转换为多列

4si2a6ki  于 2022-12-10  发布在  SQL Server
关注(0)|答案(2)|浏览(269)

I have table look like below. I have two type of package type for a single product. But some product has only UPC
| Product No | Barcode | Package Type | Length | Width |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| 19 | 123456 | UPC | 6 | 2 |
| 19 | 789101 | UCC | 3 | 4 |
| 20 | 987568 | UPC | 2 | 5 |
| 20 | 869584 | UCC | 7 | 8 |
| 21 | 869584 | UPC | 8 | 3 |
But I need a loke like this table. Basically I want to keep a row only where package type = UCC when the product have two package type. But when there is only one package type ( e.g. product no 21) then I need to keep Package type= UPS too. Then I need to keep length and width for both package type.
| Product No | Barcode | Package Type | UCC Length | UCC Width | UPC Length | UPC Width |
| ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ |
| 19 | 789101 | UCC | 3 | 4 | 6 | 2 |
| 20 | 869584 | UCC | 7 | 8 | 2 | 5 |
| 21 | 869584 | UPC | NA | NA | 8 | 3 |
I've been struggling how to do it in a SQL. If any help please it would be appreciated

ix0qys7i

ix0qys7i1#

使用窗口函数根据“Package Type”按字母顺序排列结果:

WITH ranked_products AS (SELECT *,
       ROW_NUMBER() OVER (PARTITION BY ProductNo
                          ORDER BY PackageType asc)
                    AS row_number
FROM products
) select *
FROM ranked_products
WHERE
  row_number = 1

**注:**这不会排除只有UCC的相同产品编号。

xuo3flqw

xuo3flqw2#

这会给你你想要的输出。值得注意的是,这可能不是一个很好的解决方案,因为它不容易扩展-如果你在某个时候需要处理第三,第四,第五个包类型,它会很快变得混乱。你可能会想看看使用PIVOT。但如果你很高兴它只是两个包类型,这是简单的,它应该是明确的代码在做什么。

CREATE TABLE #data (ProductNo INT,Barcode INT,PackageType VARCHAR(3),Length INT, Width INT);

INSERT INTO #data VALUES
(19,    123456  ,'UPC', 6,  2),
(19,    789101  ,'UCC', 3,  4),
(20,    987568  ,'UPC', 2,  5),
(20,    869584  ,'UCC', 7,  8),
(21,    869584  ,'UPC', 8,  3);

WITH ucc AS 
(
    SELECT ProductNo, Barcode, PackageType, Length, Width 
    FROM #data 
    WHERE PackageType = 'UCC'
),
upc AS 
(
    SELECT ProductNo, Barcode, PackageType, Length, Width 
    FROM #data 
    WHERE PackageType = 'UPC'
)
SELECT COALESCE(ucc.ProductNo, upc.ProductNo) AS ProductNo,
    COALESCE(ucc.Barcode, upc.Barcode) AS Barcode,
    COALESCE(ucc.PackageType, upc.PackageType) AS PackageType,
    ucc.Length AS UCCLength,
    ucc.Width AS UCCWidth,
    upc.Length AS UPCLength,
    upc.Width AS UPCWidth
FROM ucc 
FULL OUTER JOIN upc ON upc.ProductNo = ucc.ProductNo;

相关问题