/*汇总表:单据编号、票号*/
if OBJECT_ID('csdnhzb')is not null drop table csdnhzb
create table csdnhzb(djbh char(10),ph char(10))
insert into csdnhzb
select 'dj123','ph001' union all
select 'dj123','ph002' union all
select 'dj123','ph003'
/*明细表:单据编号、商品名称、(每一次)收款金额*/
if OBJECT_ID('csdnmxb')is not null drop table csdnmxb
create table csdnmxb(djbh char(10),mc char(10),je decimal(14,2))
insert into csdnmxb
select 'dj123','第一个名称','100.00' union all
select 'dj123','第一个名称','200.00' union all
select 'dj123','第一个名称','300.00'
/*求SQL语句,SQL查询需要这样显示结果*/
djbh ph mc je
----- ----- ----- -----
dj123 ph001 第一个名称 100.00
dj123 ph002 第一个名称 200.00
dj123 ph003 第一个名称 300.00
------解决方案--------------------
现在的数据库,都已经放弃所谓的记录顺序了,必须按某些字段排序,所以楼主的数据缺乏必要的联系,现发回重审,请补充侦察吧。
------解决方案--------------------
--sql 2008以上的
WITH cte
AS
(
SELECT t1.djbh,t1.ph,t2.mc,t2.je,ROW_NUMBER() OVER(PARTITION BY t1.djbh,t2.mc,t2.je ORDER BY t2.djbh) rn
FROM csdnhzb t1 INNER JOIN csdnmxb t2 ON t1.djbh=t2.djbh
)
SELECT djbh,ph,mc,je FROM cte WHERE rn=1
------解决方案--------------------
select a.djbh,a.ph,b.mc,b.je
from
(select djbh,ph,row_number() over(partition by djbh order by getdate()) 'rn'
from csdnhzb) a
inner join
(select djbh,mc,je,row_number() over(partition by djbh order by getdate()) 'rn'
from csdnmxb) b on a.djbh=b.djbh and a.rn=b.rn
/*
djbh ph mc je
---------- ---------- ---------- --------------
dj123 ph001 第一个名称 100.00
dj123 ph002 第一个名称 200.00
dj123 ph003 第一个名称 300.00
(3 row(s) affected)
*/