SQL Server 2008 R2 - 按条件选择主数据和详细数据

时间:2014-05-19 07:58:35

标签: sql sql-server sql-server-2008

我有如下所示的Master和Detail Table,需要生成报告。主要思想是在每个Master_ID组中选择具有唯一值的Code,并将此Code与Master的ID和Revenue合并。

如何使用SQL实现此目的。谢谢!

Master
ID      Revenue
A       100
B       200
C       300
D       400
E       500
F       600

Detail      
Master_ID   No  Code
A           1   code123
A           2   N/A
B           1   N/A
C           1   code456
C           2   code789
C           3   N/A
D           1   N/A
E           1   code321
E           2   code321

Report      
No  Revenue Code
A   100     code123
B   200     N/A
C   300     N/A
D   400     N/A
E   500     code321
F   600     N/A

1 个答案:

答案 0 :(得分:0)

试试这个:

;with cte as
(select master_id mid, count(distinct code) dc
 from details 
 where code <> 'N/A'
 group by master_id),

filtered as
(select d.master_id fid, 
 case when c.dc = 1 then d.code else 'N/A' end fcode, 
 row_number() over (partition by d.master_id order by d.master_id) rn 
from details d
left join cte c on c.mid = d.master_id)

select m.id, m.revenue,isnull(f.fcode,'N/A') from 
master m 
left outer join filtered f
on m.id = f.fid
where isnull(f.rn,1) = 1