0
這與this question和this question類似,但我的情況稍有不同,我無法使其工作。與一列不同,按計算列排列
我正在使用SQL Server 2016.我現有的查詢是在下面,它工作正常。它選擇Interest
行,並按感興趣的數量Post
對它們進行排序。
-- this is in a stored procedure, variables are valid
select i.[Id], i.[Name], i.[Description],
(
select count(*) from [Post] p where p.[InterestId] = i.[Id] and p.[CreatedAt] >= @AfterTime
) as PostCount
from Interest i
order by PostCount desc
offset (@Start - 1) rows fetch next (@ReturnNum) rows only
我現在想改變這一點。 Interest表中有另一列InterestCategoryId
;這是與InterestCategory
建立1:M關係的外鍵。我想獲得與以前相同的信息,但僅限於一個InterestCategoryId
- 我只能得到每個類別的一個結果。我怎樣才能做到這一點?我正在嘗試這個代碼,但它會拋出一個錯誤,PostCount
不是一個有效的列。
select [Id], [Name], [Description], PostCount
from
(
select [Id], [Name], [Description],
(
select count(*) from [Post] po where po.[InterestId] = [Id] and po.[CreatedAt] >= @AfterTime
) as PostCount,
row_number() over(partition by [InterestCategoryId] order by PostCount desc) rn
from [Interest]
) i
where rn = 1
order by PostCount desc
offset (@Start - 1) rows fetch next (@ReturnNum) rows only
示例感興趣的數據如下。如果我們假設利息ID 1的帖子數多於2,我會希望返回利息1,3,4。
ID | Name | Description | InterestCategoryId
---|------|-------------|-------------------
1 | Test | Test int | 1
2 | Tes2 | Test int2 | 1
3 | Tes3 | Test int3 | 2
4 | Tes4 | Test int4 | 3
一個簡單的'min'聚合函數將做到這一點。我認爲。試試這個:'select min(id)id,min(Name)name,min(Description)描述,來自Interest的min(InterestCategoryId)'既然你說只需要返回第1,3和4行就可以了。 –
@JorgeCampos它可能是2,3和4,但如果興趣2的帖子數大於1。 – vaindil