好象不是很难,怎么就想不通?哎...
表A
id BuyID
1 001
2 002
3 001
4 002
5 001
6 003
7 004
表B
id Name
2 A
3 B
4 C
5 A
6 D
7 B
8 A
说明:
1:先根据BuyID算出 来了几次 001(3次),002(2次),003(1次), 004(1次)做为条件.
2:根据Name 算出 该Name 存在了几次 A(3),B(2),C(1),D(1)
3:例如结果
------------
选择 1次
Name 次数
D 1
B 2
-------
选择 2次
Name 次数
A 3
------解决方案----------------------創建測試環境
Create Table A
(id Int,
BuyID Char(3))
Insert A Select 1, '001 '
Union All Select 2, '002 '
Union All Select 3, '001 '
Union All Select 4, '002 '
Union All Select 5, '001 '
Union All Select 6, '003 '
Union All Select 7, '004 '
Create Table B
(id Int,
Name Varchar(10))
Insert B Select 2, 'A '
Union All Select 3, 'B '
Union All Select 4, 'C '
Union All Select 5, 'A '
Union All Select 6, 'D '
Union All Select 7, 'B '
Union All Select 8, 'A '
GO
--測試
Select
B.Name,
Count(B.id) As 次数
From
B
Inner Join
B C
On B.Name = C.Name
Inner Join
A
On A.id = C.id
Inner Join
(Select BuyID From A Group By BuyID Having Count(id) = 2) D --只需修改2
On A.BuyID = D.BuyID
Group By
B.Name
Select
B.Name,
Count(B.id) As 次数
From
B
Inner Join
B C
On B.Name = C.Name
Inner Join
A
On A.id = C.id
Inner Join
(Select BuyID From A Group By BuyID Having Count(id) = 1) D --只需修改1
On A.BuyID = D.BuyID
Group By
B.Name
GO
--刪除測試環境
Drop Table A, B
--結果
/*
Name 次数
A 3
C 1
Name 次数
B 2
D 1
*/