在一行SQL上合并结果

时间:2013-01-18 10:09:11

标签: sql sql-server

我想整合一对多的关系,这些关系在不同的行上输出到一行。

(select rate_value1 
      FROM xgenca_enquiry_event 
       INNER JOIN  xgenca_enquiry_iso_code_translation 
             ON 
       xgenca_enquiry_event_rate.rate_code_id 
           = xgenca_enquiry_iso_code_translation.id  
       where xgenca_enquiry_event_rate.event_id = xgenca_enquiry_event.id 
              and ISO_code = 'PDIV') as PDIVrate, 
(select rate_value1 
       FROM xgenca_enquiry_event 
        INNER JOIN xgenca_enquiry_iso_code_translation 
              ON 
         xgenca_enquiry_event_rate.rate_code_id 
           = xgenca_enquiry_iso_code_translation.id  
        where xgenca_enquiry_event_rate.event_id = xgenca_enquiry_event.id 
              and ISO_code = 'TAXR') as TAXrate

PDIVrate    TAXrate
NULL        10.0000000
0.0059120   NULL

我想将结果放在一行。任何帮助将不胜感激。 感谢。

2 个答案:

答案 0 :(得分:2)

您可以使用聚合函数执行此操作:

select 
  max(case when ISO_code = 'PDIV' then rate_value1 end) PDIVRate,
  max(case when ISO_code = 'TAXR' then rate_value1 end) TAXRate
FROM xgenca_enquiry_event_rate r 
INNER JOIN  xgenca_enquiry_iso_code_translation t
  ON r.rate_code_id = t.id  
INNER JOIN xgenca_enquiry_event e
  ON r.event_id = e.id 

看起来你正在加入三个表在查询中是相同的。这会使用连接将其合并为单个查询。

答案 1 :(得分:0)

看这里: Can I Comma Delimit Multiple Rows Into One Column?

使用STUFF在SQL Server中模拟Oracle的LISTAGG():

SELECT Column1,
  stuff((
   SELECT ', ' + Column2
     FROM tableName as t1
      where t1.Column1 = t2.Column1
       FOR XML PATH('')
     ), 1, 2, '')
 FROM tableName as t2
GROUP BY Column1
/

从这里复制:https://github.com/jOOQ/jOOQ/issues/1277