我有一张表:
Name Size
--------------------------------------
backup_20160426000000.comp.trn 1
backup_20160426001000.comp.trn 2
backup_20160426002000.comp.trn 4
(..)
backup_20160426230000.comp.trn 4
backup_20160426231000.comp.trn 5
我需要能够GROUP BY文本BY“小时”(20160426000000将是小时0,20160426010000将是小时1等)然后总结总大小。
输出应为:
backup_20160426000000.comp.trn 7
(..)
backup_20160426230000.comp.trn 9
目前我有:
SELECT
SUBSTRING(dbo.CLName.NAME, PATINDEX('%2016%', dbo.CLName.NAME), 14), size
FROM
dbo.CLName
GROUP BY
substring(Name, 1, 15)
答案 0 :(得分:3)
由于所有字符串都具有相同的格式,因此您可以使用substring
对其进行appart并重新构建,因为您已完成部分操作:
SELECT
SUBSTRING(name, 1, 15) + '0000.comp.trn', SUM(size)
FROM
dbo.CLName
GROUP BY
SUBSTRING(name, 1, 15)
答案 1 :(得分:0)
使用SUBSTRING
功能获取小时。
SELECT MIN(Name) AS Name, SUM(Size) AS Size_Sum
FROM TblBackup
GROUP BY SUBSTRING(Name, 16, 2)
输出结果:
Name Size_Sum
--------------------------------------------
backup_20160426000000.comp.trn 7
backup_20160426230000.comp.trn 9
答案 2 :(得分:0)
您可以向表中添加计算字段以获取日期和时间,如下所示。 (注意:我将分钟设置为零,假设您只对整个小时感兴趣,但可以更改。)
CREATE TABLE dbo.MyBackup
(
BackupName nvarchar(30) NOT NULL PRIMARY KEY,
Size int NOT NULL,
BackupDateTime AS CAST(SUBSTRING(BackupName, 8, 4) + N'-' + SUBSTRING(BackupName, 12, 2) + N'-' + SUBSTRING(BackupName, 14, 2) + N' ' + SUBSTRING(BackupName, 16, 2) + N':00' AS datetime2(0))
);
GO
然后添加样本数据。
INSERT INTO dbo.MyBackup (BackupName, Size)
VALUES (N'backup_20160426000000.comp.trn', 1),
(N'backup_20160426001000.comp.trn', 2),
(N'backup_20160426002000.comp.trn', 4),
(N'backup_20160426230000.comp.trn', 4),
(N'backup_20160426231000.comp.trn', 5);
然后,您可以按BackupDateTime进行选择和分组,并将大小相加。
SELECT BackupDateTime, SUM(Size) AS 'Size'
FROM dbo.MyBackup
GROUP BY BackupDateTime
ORDER BY BackupDateTime;
或者完全按照您的展示显示它。
SELECT N'backup_' + FORMAT(YEAR(BackupDateTime), '0000') + FORMAT(MONTH(BackupDateTime), '00') + FORMAT(DAY(BackupDateTime), '00') + FORMAT(DATEPART(hour, BackupDateTime), '00') + FORMAT(DATEPART(minute, BackupDateTime), '00') + N'00.comp.trn' AS 'Name', SUM(Size) AS 'Size'
FROM dbo.MyBackup
GROUP BY BackupDateTime
ORDER BY BackupDateTime;