我有以下查询-
SELECT sub.Name, sub.SizeGB, sub.DriveName,
RANK() OVER
(PARTITION BY sub.DriveName ORDER BY sub.Name DESC) AS Rank
FROM
(
SELECT NAME,
SUBSTRING(physical_name, 0, 2) AS DriveName,
SIZE * 8 / (1024*1024) AS SizeGB
FROM sys.master_files
WHERE database_id > 4
) as sub
GROUP BY sub.DriveName, sub.Name, sub.SizeGB
这给了我下面的输出
我想找到特定驱动器上所有文件所占用的空间。因此,我们的想法是基于SUM
列来SizeGB
Rank
列。有没有一种方法可以编辑当前查询以达到所需的结果。
输出应如下所示-
答案 0 :(得分:2)
您可以在外部查询中再次进行汇总以获得驱动器大小的总和。使用PARTITIONED SUM将使您在分区窗口内重复值。
SELECT
*,
TotalSize=SUM(SizeGB) OVER (PARTITION BY DriveName)
FROM
(
SELECT sub.Name, sub.SizeGB, sub.DriveName,
RANK() OVER
(PARTITION BY sub.DriveName ORDER BY sub.Name DESC) AS Rank
FROM
(
SELECT NAME,
SUBSTRING(physical_name, 0, 2) AS DriveName,
SIZE * 8 / (1024*1024) AS SizeGB
FROM sys.master_files
WHERE database_id > 4
) as sub
GROUP BY sub.DriveName, sub.Name, sub.SizeGB
)AS X
或作为详细信息查询的一部分
SELECT sub.Name, sub.SizeGB, sub.DriveName,
RANK() OVER
(PARTITION BY sub.DriveName ORDER BY sub.Name DESC) AS Rank,
SUM(SizeGB) OVER (PARTITION BY DriveName) AS TotalSize
FROM
(
SELECT NAME,
SUBSTRING(physical_name, 0, 2) AS DriveName,
SIZE * 8 / (1024*1024) AS SizeGB
FROM sys.master_files
WHERE database_id > 4
) as sub
GROUP BY sub.DriveName, sub.Name, sub.SizeGB
答案 1 :(得分:1)
This should retrieve it:
; with cte
AS
(SELECT sub.Name, sub.SizeGB, sub.DriveName,
RANK() OVER
(PARTITION BY sub.DriveName ORDER BY sub.Name DESC) AS Rank
FROM
(
SELECT NAME,
SUBSTRING(physical_name, 0, 2) AS DriveName,
SIZE * 8 / (1024*1024) AS SizeGB
FROM sys.master_files
WHERE database_id > 4
) as sub
GROUP BY sub.DriveName, sub.Name, sub.SizeGB
)
select * from cte
JOIN (SELECT sum(sizeGB) sum, drivename dn from cte GROUP BY drivename) a
ON a.dn = cte.drivename