sql查询按范围分组文件大小,总和为

时间:2015-12-11 20:04:01

标签: sql sql-server

sql(sql server)查询按范围分组文件大小并输出总和 输出应该有 文件大小以Megs为单位  < 20,20-50,50-100,100 + 我需要每个括号的计数和总和

表MyFiles(ID,filesize) 产量 < 20,< 20计数,20-50,20-50计数,50-100,50-100计数,100 +,100 +计数

我不确定如何将它们分组到范围中并获得总和和计数

2 个答案:

答案 0 :(得分:3)

您可以使用案例陈述,但如果您的标准(条带)要改变,它会变得复杂。

我会使用内存表来保存范围,并在数据表上进行简单的连接,因为这样可以使结束查询变得非常简单,并且可以更容易地更改条带的更改:

 -- In memory table to hold ranges
 DECLARE @Range TABLE(
    Id INT
    ,MinRange INT
    ,MaxRange INT 
    ,Dsc VARCHAR(255)
)

INSERT INTO @Range VALUES(1, 0, 20, '< 20')
INSERT INTO @Range VALUES(2, 20, 50, '20 - 50')
INSERT INTO @Range VALUES(3, 50, 100, '50 - 100')
INSERT INTO @Range VALUES(4, 100, NULL, '100 +')

-- Mock of your Data Table
DECLARE @Data TABLE(
    Id INT,
    FileSize INT)

INSERT INTO @Data VALUES(1, 100)
INSERT INTO @Data VALUES(2, 101)
INSERT INTO @Data VALUES(3, 19)
INSERT INTO @Data VALUES(4, 50)
INSERT INTO @Data VALUES(5, 99)

-- Group By Query to determine count and size of files by range
SELECT R.Dsc
     , SUM(D.FileSize) as TotalFileSize
     , COUNT(*) as NumberOfFiles FROM @Data D
    INNER JOIN @Range R ON (D.FileSize >= R.MinRange AND D.FileSize < R.MaxRange)
                        OR (D.FileSize >= R.MinRange AND R.MaxRange IS NULL)
        GROUP BY R.Dsc

上述结果:

 +----------+---------------+---------------+
 |   Dsc    | TotalFileSize | NumberOfFiles |
 +----------+---------------+---------------+
 | < 20     |            19 |             1 |
 | 100 +    |           201 |             2 |
 | 50 - 100 |           149 |             2 |
 +----------+---------------+---------------+

答案 1 :(得分:0)

我最终使用了一个案例陈述,一旦我看到它 - 这很容易做到。 我简化了我正在使用的内容,但显示了sql

select  GroupName,
sum(
case when FileSize between 1 and (1024 * 1024 * 20) then FileSize else 0 end
) as '< 20', 
SUM(
case when FileSize between 1 and (1024 * 1024 * 20) then 1 else 0 end
) as '< 20 count',
sum(
case when FileSize between (1024 * 1024 * 20 -1) and (1024 * 1024 * 50) then FileSize else 0 end
) as '20 - 50', 
SUM(
case when FileSize between (1024 * 1024 * 20 -1) and (1024 * 1024 * 50) then 1 else 0 end
) as '20 - 50 count',
sum(
case when FileSize between (1024 * 1024 * 50 -1) and (1024 * 1024 * 100) then FileSize else 0 end
) as '50 - 100', 
SUM(
case when FileSize between (1024 * 1024 * 50 -1) and (1024 * 1024 * 100) then 1 else 0 end
) as '50 - 100 count',
sum(
case when FileSize > (1024 * 1024 * 100 -1)  then FileSize else 0 end
) as '100+', 
SUM(
case when FileSize > (1024 * 1024 * 100 -1) then 1 else 0 end
) as '100+ count',
sum(
FileSize 
) as 'Total Size', 
SUM(
case when FileSize > 0 then 1 else 0 end
) as 'Total Count'
 FROM FileEntries
Group By GroupName