数据库中 根据 【组合分类】 查询 数据 怎么写SQL ???
分类表(Categroy)数据:
CID CName
-------------
1 A
2 B
3 C
主表(BankData)数据:
MID MName CID CODE
------------------------
1 M 1 1
2 M 2 1
3 H 1 2
4 H 3 2
5 K 1 3
6 K 2 3
现在 我想根据 分类 A + B 查询 主表数据 结果集为:
CODE MName
------------------
1 M
3 K
-------------------------------------------------------
哪位大牛 可以帮小弟 写下? 在线等 完事立马结贴把分送上!!!
不好意思
exists前面少写了个not.
[解决办法]
if object_id('[Categroy]') is not null drop table [Categroy]
go
create table [Categroy]([CID] int,[CName] varchar(1))
insert [Categroy]
select 1,'A' union all
select 2,'B' union all
select 3,'C' union all
select 4,'D' union all
select 5,'E' union all
select 6,'F'
--> 测试数据:[BankData]
if object_id('[BankData]') is not null drop table [BankData]
go
create table [BankData]([MID] int,[MName] varchar(1),[CID] int,[CODE] int)
insert [BankData]
select 1,'M',1,1 union all
select 2,'M',2,1 union all
select 3,'H',1,2 union all
select 4,'H',3,2 union all
select 5,'K',1,3 union all
select 6,'K',2,3 union all
select 7,'K',4,3 union all
select 8,'K',5,3 union all
select 9,'F',1,4 union all
select 10,'F',4,4 union all
select 11,'S',1,5 union all
select 12,'S',5,5 union all
select 13,'X',1,6
SELECT Mname,code
FROM (
SELECT Mname,code,ROW_NUMBER()OVER(PARTITION BY code ORDER BY mid)id
FROM [BankData] b
INNER JOIN (
SELECT [cid]
FROM [Categroy]
WHERE [cname] IN ( 'A', 'B' ) ) c ON b.cid=c.cid
)a
GROUP BY Mname,code
HAVING MAX(id)=(SELECT COUNT(1) FROM [Categroy]
WHERE [cname] IN ( 'A', 'B' ) )
/*
Mname code
----- -----------
M 1
K 3
*/