TSQL通过百分比查询将“其他”添加到GROUP

时间:2011-04-17 15:30:26

标签: sql tsql

我如何构建一个查询,将某个百分比以下的任何内容分类为其他?

例如:

Select Country, (COUNT(Country)*100 / (Select COUNT(*) From Logs)) as Perc
FROM Logs
Group by Country
HAVING (COUNT(Country)*100 / (Select COUNT(*) From Logs)) > 5
ORDER BY Perc DESC

我如何添加一行“其他”,其中所有内容的总和小于6%?

3 个答案:

答案 0 :(得分:3)

另一种方法

;WITH Logs(Country) AS
(
SELECT TOP 10 'UK' FROM sys.objects UNION ALL
SELECT TOP 10 'US' FROM sys.objects UNION ALL
SELECT TOP 1 'Timbuktu' FROM sys.objects
),
GroupedLogs AS
(
SELECT Country, 
      (COUNT(Country) * 100.0 / (SELECT COUNT(*) FROM Logs)) AS Perc
FROM Logs
GROUP BY Country
)
SELECT CASE WHEN Perc<6 THEN 'Other' ELSE Country END AS Country, 
       SUM(Perc) AS Perc
FROM GroupedLogs
GROUP BY CASE WHEN Perc<6 THEN 'Other' ELSE Country END

答案 1 :(得分:1)

我认为你需要一个UNION。没有经过测试,但有类似的事情:

SELECT * FROM 
(
    Select 
        Country, 
        (COUNT(Country)*100 / (Select COUNT(*) From Logs)) as Perc 
    FROM 
        Logs 
    Group by 
        Country 
    HAVING 
        (COUNT(Country)*100 / (Select COUNT(*) From Logs)) >= 6    

    UNION

    Select 
        'Other' as Country, 
        (COUNT(Country)*100 / (Select COUNT(*) From Logs)) as Perc 
    FROM 
        Logs 
    HAVING 
        (COUNT(Country)*100 / (Select COUNT(*) From Logs)) < 6 
)
ORDER BY 
    Perc DESC

答案 2 :(得分:0)

或尝试以下方面的内容。这里的百分比是在CTE中计算的:

DECLARE @countries TABLE (name varchar(16), hit INT);


INSERT INTO @countries
VALUES
('UK',1),
('UK',1),
('UK',1),
('UK',1),
('UK',1),
('UK',1),
('UK',1),
('UK',1),
('UK',1),
('UK',1),
('FRA',1),
('FRA',1),
('FRA',1),
('FRA',1),
('FRA',1),
('USA',1),
('MEX',1);

WITH MY_PERCENTAGES AS
(
    SELECT name, 
                CAST(count(*) AS NUMERIC(5,2)) 
                / 
                CAST(SUM(count(*)) OVER() AS NUMERIC(5,2)) * 100.
             AS percentage
    FROM @countries
    GROUP BY name
)
SELECT
    name,
    SUM (percentage) AS percentages
FROM 
(
    SELECT 
        CASE 
        WHEN percentage <6 THEN
            'OTHER'
        ELSE
            name
        END AS name,
        percentage
    FROM MY_PERCENTAGES
) TMP
GROUP BY name;