将多行合并为一行 - SQL Server 2005

时间:2013-06-10 17:19:35

标签: sql sql-server sql-server-2005

SQL查询是:

select 147443 as DPID, 0 as CoID, 'ABC2431953D' as MID
union 
select 147443 as DPID, 176821 as CoID, '' as MID

结果应为:

147443, 176821, ABC2431953D

我该怎么做?

2 个答案:

答案 0 :(得分:0)

您只需要加入结果集

with a as (
   select 147443 as DPID, 0 as CoID, 'ABC2431953D' as MID
), b as (
   select 147443 as DPID, 176821 as CoID, '' as MID
)
select a.DPID, b.CoID, a.MID
from a
inner join b
    on a.DPID = b.DPID

答案 1 :(得分:0)

尝试使用Max之类的

;WITH Temp (DPID, COID, MID) 
     AS ((SELECT 147443        AS DPID, 
                 0             AS CoID, 
                 'ABC2431953D' AS MID) 
         UNION 
         (SELECT 147443 AS DPID, 
                 176821 AS CoID, 
                 ''     AS MID)) 
SELECT MAX(DPID)AS DPID, 
       MAX(COID)AS CoID, 
       MAX(MID) AS MID 
FROM   Temp