简体   繁体   English

如何在SQL Server中将两行合并为一行

[英]How can I merge two rows into one row in SQL Server

My SQL query output is like this, I need to be this in one row. 我的SQL查询输出是这样的,我需要排成一行。

 iProductM  iProductO   UnitCostM   UnitCostO
    7065    NULL         30.67      NULL
    NULL    7065         NULL       29.78

Required output: 要求的输出:

iProductM   iProductO   UnitCostM   UnitCostO
        7065     7065        30.67      29.78

My query is as follows: 我的查询如下:

SELECT 
    coalesce(iProductM, iProductO) as P,
    coalesce(UnitCostM, UnitCostO) as U  
FROM 
    ViewForCostAll 
WHERE
    iProductO = 7065 OR iProductM = 7065

But my output is still in two rows: 但是我的输出仍然是两行:

P       U
7065    30.67
7065    29.78

Can anyone help me? 谁能帮我?

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

You can use one column if another is null and then use DISTICNT to remove duplicates 如果另一列为空,则可以使用一列,然后使用DISTICNT删除重复项

A join is what you do to combine rows. 联接是您合并行所要做的。 Once the join is done, you can compare values within the (internal resulting) row, and output selected results. 连接完成后,您可以比较(内部结果)行中的值,并输出选定的结果。 This query only works for the 2 rows you asked about. 该查询仅适用于您询问的2行。 If your data has more rows, let's see them and make a query that works for your actual data. 如果您的数据有更多行,让我们看一下并进行查询以适合您的实际数据。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM