[英]How can I merge two rows into one row in SQL Server
我的SQL查詢輸出是這樣的,我需要排成一行。
iProductM iProductO UnitCostM UnitCostO
7065 NULL 30.67 NULL
NULL 7065 NULL 29.78
要求的輸出:
iProductM iProductO UnitCostM UnitCostO
7065 7065 30.67 29.78
我的查詢如下:
SELECT
coalesce(iProductM, iProductO) as P,
coalesce(UnitCostM, UnitCostO) as U
FROM
ViewForCostAll
WHERE
iProductO = 7065 OR iProductM = 7065
但是我的輸出仍然是兩行:
P U
7065 30.67
7065 29.78
誰能幫我?
SELECT DISTINCT
coalesce(iProductM, iProductO) as iProductM,
coalesce(iProductO, iProductM) as iProductM,
coalesce(UnitCostM, UnitCostO) as UnitCostM,
coalesce(UnitCostO, UnitCostM) as UnitCostO
FROM
ViewForCostAll
WHERE
iProductO = 7065 OR iProductM = 7065
如果另一列為空,則可以使用一列,然后使用DISTICNT刪除重復項
聯接是您合並行所要做的。 連接完成后,您可以比較(內部結果)行中的值,並輸出選定的結果。 該查詢僅適用於您詢問的2行。 如果您的數據有更多行,讓我們看一下並進行查詢以適合您的實際數據。
SELECT
isNull(V1.iProductM, V2.iProductM) as iProductM,
isNull(V1.iProductO, V2.iProductO) as iProductO,
isNull(V1.UnitCostM, V2.UnitCostM) as UnitCostM,
isNull(V1.UnitCostO, V2.UnitCostO) as UnitCostO
FROM
ViewForCostAll V1
LEFT JOIN
ViewforCostAll V2 on (V2.iProductM is null)
WHERE
V1.iProductO = 7065
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.