TSQL - 选择Top 10&将其余部分显示为'其他'

时间:2014-10-17 08:20:17

标签: sql sql-server-2008 tsql

我有一个浏览器“名称”s& “版本” S

Name    Version
Safari  5.1
Safari  4.0
IE      5.0
IEMob   9.0

我正在编写一个查询,以返回允许的十大最常见浏览器,并将任何其他浏览器标记为“其他”

到目前为止,这是我的存储过程,它返回了我想要的前10个浏览器,并创建了一个“其他”行,但没有填充它。

ALTER PROCEDURE [dbo].[GetUncommonBrowserCount]
    @StartDate datetime = NULL,
    @EndDate datetime = NULL,
    @Domain varchar(255) = NULL
AS
BEGIN

    SET NOCOUNT ON;

UPDATE dbo.Browsers SET [Name] = 'IE' WHERE [Name] = 'InternetExplorer'  

SELECT Name, Count, [Version] FROM
(
    SELECT TOP 10 
        Name,
        COUNT(Name) AS [Count],
        [Version]
    FROM 
        dbo.GetCommonBrowserAccessEvents
    WHERE 
        NOT
        (   
            Name = 'Chrome' OR [Name] = 'Firefox' OR Name = 'IE' AND CAST(SUBSTRING([Version], 1, CHARINDEX('.', [Version]) - 1) AS INT) > 7
        )
        AND
        (
            @StartDate IS NULL OR [Date] > @StartDate
        )
        AND
        (
            @EndDate IS NULL OR [Date] < @EndDate
        )
        AND
        (
            @Domain IS NULL OR DomainName = @Domain
        )
        GROUP BY 
            Name,
            [Version]
        ORDER BY 
            COUNT(Name) DESC
) AS A1

    UNION ALL

    SELECT
        'Other' AS Name,
        COUNT(Name) AS [Count],
        [Version] = NULL
    FROM 
        dbo.GetCommonBrowserAccessEvents
    WHERE
        Name NOT IN (SELECT TOP 10
            Name
        FROM
            dbo.GetCommonBrowserAccessEvents
        GROUP BY 
            Name
        ORDER BY 
            COUNT(Name) DESC)
    END

如果你能看到我做错了什么以及如何解决它,请告诉我。这些是我从大表中得到的结果。其他的null版本是故意的,因为我正在制作包含此数据的饼图,并希望将“其他”作为单个切片。

Name  Count Version
Safari  46  5.1
Mozilla 18  0.0
Safari  16  5.0
IE      12  7.0
Safari  12  0.0
Safari  9   6.0
IEMob   8   9.0
IEMob   8   10.0
IE      8   6.0
IE      1   3.2A
Other   0   NULL

1 个答案:

答案 0 :(得分:1)

尝试更改

        GROUP BY 
        Name

        GROUP BY 
        Name,
        [Version]

在你的UNION ALL的第二部分