我的两个表没有主键但是有三个列相同的字段。我从两个表中选择并得出如下结果:
表1:
No Code Row Price
001 0001 1 100
001 0001 2 200
002 0001 1 300
表2:
No Code Row Qty Date
001 0001 1 10 2016
001 0001 2 20 2017
结果表:
No Code Row Price Qty Date Row2
001 0001 1 100 10 2016 1
001 0001 1 100 10 2016 2
001 0001 2 200 20 2017 1
001 0001 2 200 20 2017 2
我的SQL:
Select
T2.No,T2.Code,T2.Row,T1.Price,T2.Qty,T2.Date,T1.Row as Row2
From Table1 T1 JOIN Table2 T2
On T1.No = T2.No
And T1.Code = T2.Code
Order by T2.Code,T1.Row
我希望结果像这样出来:
No Code Row Price Qty Date Row2
001 0001 1 100 10 2016 1
001 0001 2 200 20 2017 2
我应该写什么SQL?请指教我..我是SQL的新手。 如果我像这样修改查询:
Select
T2.No,T2.Code,T2.Row,T1.Price,T2.Qty,T2.Date,T1.Row as Row2
From Table1 T1 JOIN Table2 T2
On T1.No = T2.No
And T1.Code = T2.Code
And T1.Row = T2.Row
Order by T2.Code,T1.Row
没有任何结果...... 请帮帮我。
先谢谢。
答案 0 :(得分:2)
使用左连接可以解决您的问题。
SELECT T2.No,T2.Code,T2.Row,T1.Price,T2.Qty,T2.Date,T1.Row as Row2
FROM Table2 T2
LEFT JOIN Table1 T1 ON T1.No = T2.No
And T1.Code = T2.Code
And T1.Row = T2.Row
ORDER BY T2.Code,T1.Row
答案 1 :(得分:0)
如果您使用的是sql server,请尝试此查询
Select * from
(
Select *,row_number()over(partition by date order by no) as row2 from
(
Select
Tbl1.*,tbl2.qty,tbl2.date
From tbl1 inner join tbl2 on tbl.no=tbl2.no
) as ab
)as bc where row2=1
我希望这会对你有所帮助。