0

我有这两张表A和B

A:

id|name
1 | AAA
2 | BBB
3 | CCC

乙:

id|a_ref_id|name2
1 |1       |aaa
2 |1       |aAa
3 |2       |bbb
4 |3       |ccc
5 |3       |cCc

该表可以通过 连接a_ref_id

我想要这样的输出:

A_id|A_name|B_id|B_name2|A_id_occurencse_in_this_query
1   |AAA   |1   |aaa    |1
1   |AAA   |2   |aAa    |2
2   |BBB   |3   |bbb    |1
3   |CCC   |4   |ccc    |1
3   |CCC   |5   |cCc    |2

最后一栏是我的问题。

加入很容易,但我不知道如何获得最后一列。我曾尝试使用COUNT, GROUP BY,HAVING等,但没有运气。

有任何想法吗?

4

2 回答 2

1

对于 MS-SQL,您可以使用ROW_NUMBER()PARTITION

SELECT
  a.ID as A_ID,
  a.Name as A_Name,
  B.ID as B_ID,
  B.NAME2 as B_Name2,
  ROW_NUMBER() OVER(PARTITION By A.ID ORDER BY A.ID, B.ID) as A_id_occurencse_in_this_query
FROM A
JOIN B
  ON a.ID = b.a_ref_id
于 2013-01-21T15:53:06.737 回答
0
select *
from 
(select a.id , min(a_ref_id) as a_ref_id, min(name2) as name , count(1) as A_id_occurencse
from B a join B b on a.id < b.id 
group by a.id) t join A a on t.a_ref_id = a.id 
于 2013-01-21T15:42:35.323 回答