我正在尝试从两个类别中进行选择,但我希望通过对每个five
categories.
进行分组来在类别之间进行切换
以下是表格
SELECT MC.main_category_id, MC.main_category_name, MC.order_by_num AS MC_Order,
C.category_id, C.category_name, C.order_by_num AS C_Order, C.gift, I.item_id, I.model_num, I.item_title, B.brand_name, I.price, I.suggested_price, i.description
FROM dbo.tblMainCategories AS MC
INNER JOIN dbo.tblCategories AS C ON MC.main_category_id = C.main_category_id
INNER JOIN dbo.tblItemCategories AS IC ON MC.main_category_id = IC.main_category_id
AND C.category_id = IC.category_id
INNER JOIN dbo.tblItems AS I ON IC.ic_item_id = I.item_id
INNER JOIN dbo.tblBrands AS B ON I.brand_id = B.brand_id
WHERE (MC.store_id = 14) AND (IC.store_id = 14) AND I.isActive = 1
And MC.main_category_id in (1,2)
ORDER BY MC.order_by_num, C.order_by_num, I.order_by_num,I.price
如何对此结果进行排序,应该按MainCategory 1
中的5个MainCategory 2
然后5个MainCategory 1
以及5个MainCategory 1
对其进行排序,并继续5个直到结束。
MainCategory 2
包含的项目多于MainCategory 1
。 {{1}}的其余部分也应该在底部。
答案 0 :(得分:2)
你可以尝试这样的事情。在将它们插入SQL表时,请确保您的结果按照您想要的顺序排序。将查询分成2个重复项,将结果插入到某些临时表中。然后,您可以遍历结果,将每个5插入到第三个结果表中。
以下是我使用我可以使用的数据库的方法示例。
create table #result(AccountID int, AccountTypeID int, AccountName varchar(128))
select AccountID, ab.AccountTypeID, AccountName INTO #Temp from AccountBase ab
join AccountType at on ab.AccountTypeId = at.AccountTypeId
where ab.AccountTypeId in (1)
order by AccountName
select AccountID, ab.AccountTypeID, AccountName INTO #Temp2 from AccountBase ab
join AccountType at on ab.AccountTypeId = at.AccountTypeId
where ab.AccountTypeId in (2)
order by AccountName
While ((select count(*) from #Temp) > 0 or (select count(*) from #Temp2) > 0)
begin
If (select count(*) from #Temp) > 0
Begin
insert into #result select Top(5) * from #Temp
delete top(5) from #Temp
End
If (select count(*) from #Temp2) > 0
Begin
insert into #result select Top(5) * from #Temp2
delete top(5) from #Temp2
End
End
select * from #result
drop table #Temp
drop table #Temp2
drop table #result
我相信SQL 2000支持所有内容。