我有这两个表A和B
A:
id|name
1 | AAA
2 | BBB
3 | CCC
B:
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
等,但没有运气。
任何想法?
答案 0 :(得分: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
答案 1 :(得分: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