1

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

我如何对这个结果进行排序,它应该按 5 排序,MainCategory 1然后 5排序,然后 5 排序MainCategory 2MainCategory 1并继续 5 直到结束。

MainCategory 1拥有比 更多的项目MainCategory 2。其余的MainCategory 1也应该在底部。

4

1 回答 1

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 支持一切。

于 2013-06-19T19:43:57.963 回答