2017-02-10 50 views
0

這與this questionthis 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 
+0

一個簡單的'min'聚合函數將做到這一點。我認爲。試試這個:'select min(id)id,min(Name)name,min(Description)描述,來自Interest的min(InterestCategoryId)'既然你說只需要返回第1,3和4行就可以了。 –

+0

@JorgeCampos它可能是2,3和4,但如果興趣2的帖子數大於1。 – vaindil

回答

0

這並不美觀,但它運行。我希望它能幫助你到達你想去的地方。

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 (
     select count(*) 
     from [Post] po 
     where po.[InterestId] = [Id] 
     and po.[CreatedAt] >= @AfterTime 
    ) desc) rn 
    from [Interest] 
) i 
where rn = 1 
order by PostCount desc 
offset (@Start - 1) rows fetch next (@ReturnNum) rows only 

如果您想避免重複子查詢COUNT,請嘗試這種方式。

select [Id], [Name], [Description], PostCount 
from 
( 
    select AA.Id, AA.Name, AA.Description, AA.PostCount, AA.[InterestCategoryId], 
    row_number() over(partition by [InterestCategoryId] order by PostCount desc) rn 
    from (select [Id], [Name], [Description], [InterestCategoryId], 
    (
     select count(*) 
     from [Post] po 
     where po.[InterestId] = [Id] 
     and po.[CreatedAt] >= @AfterTime 
    ) as PostCount 
    from [Interest]) AA 
) i 
where rn = 1 
order by PostCount desc 
offset (@Start - 1) rows fetch next (@ReturnNum) rows only 

感謝提醒OFFSET條款。我沒有機會經常使用它。

希望這會有所幫助。祝你好運!