declare @t table(type varchar(10),value varchar(10))
insert @t
select 'A', 'A1'
union all
select 'A', 'A2'
union all
select 'A', 'A3'
union all
select 'B', 'B1'
union all
select 'B', 'B2'
union all
select 'B', 'B3'
declare @t1 table(type varchar(10),count int)
insert @t1
select 'A', 2
union all
select 'B', 3
select * from
(
select a.*,b.count from @t a left join @t1 b on a.type=b.type
)a where right(value,1)<=count
select [Type],[Value] from
(
SELECT TableA.Type,TableA.Value,TableB.Counts,
row_number() over(PARTITION BY TableA.Type ORDER BY TableA.Type) AS [序号]
FROM TableA inner join TableB ON TableB.Type= TableA.Type
) b where b.[序号]<=b.Counts
可以在存储过程中实现。
-----------------创建测试数据表-----------------
CREATE TABLE [t] (
type varchar(10),value varchar(10)
)
insert t
select 'A', 'a'
union all select 'A', 'aa'
union all select 'A', 'aaa'
union all select 'B', 'b'
union all select 'B', 'bb'
union all select 'B', 'bbb'
CREATE TABLE [t1] (
type varchar(10),counts int
)
insert t1
select 'A', 2
union all select 'B', 3
----------------------------------------
---------以下是存储过程中的语句块儿----------
----创建临时表,用于存放结果
CREATE TABLE [#T_All] (
type varchar(10),value varchar(10)
)
declare @sql varchar(2000)
declare @type varchar(255),@counts int
----使用游标遍历,将查询结果集存储到临时表--
declare MyCursor cursor for
select type,counts from t1
open MyCursor
FETCH NEXT FROM MyCursor into @type,@counts
while @@fetch_status = 0
begin
set @sql = 'insert into #T_All(type,value) '
+' select top '+cast(@counts as varchar(10))+' type,value from t '
+' where type = '''+@type+''''
exec (@sql)
FETCH NEXT FROM MyCursor into @type,@counts
end
CLOSE MyCursor
DEALLOCATE MyCursor
--------得到结果------
select * from #T_All
--------删除测试表------,别把你自己的表删了哟 :)
drop table t
drop table t1
drop table #T_All
--不知道
with TableA([type],value) as (
select 'A', 'A1'
union all
select 'A', 'A2'
union all
select 'A', 'A3'
union all
select 'B', 'B1'
union all
select 'B', 'B2'
union all
select 'B', 'B3'
),
TableB([type],counts) as (
select 'A', 2
union all
select 'B', 3
)
select a.[type],a.value from
( select [type],value,
row_number() over(partition by type order by value) rn
from TableA
) a, TableB b
where a.rn <= b.counts
and a.[type] = b.[type]
type value
---- -----
A A1
A A2
B B1
B B2
B B3
killkill写的不错 学习了
SELECT [type],[value],ROW_NUMBER() OVER(PARTITION BY [type] ORDER BY [value]) RN
)A, TableB B WHERE A.RN<=B.[Counts] AND A.[type]=B.[type]