SELECT
	q.MetadataId AS MetadataId,
	COUNT(DISTINCT q.DataId) AS CountDataId,
	COUNT(q.VersionNumber) AS ReadyCount,
	COUNT(q.RawSize) AS RawCount,
	MAX(q.VersionNumber) AS MaxVer,
	SUM(q.ReadySize) / 1024 AS ReadySizeKb,
	SUM(q.RawSize) / 1024 AS RawSizeKb,
	MIN(q.Date) AS MinDate,
	MAX(q.Date) AS MaxDate
FROM
	(--{Выборка: ГотовыеВерсии ----------------------------------------
	SELECT
		md._MetadataId AS MetadataId,
		l._DataId AS DataId,
		v._VersionNumber AS VersionNumber,
		v._Date AS Date,
		100 + DATALENGTH(v._UserName) * 2 + DATALENGTH(v._UserFullName) * 2 + DATALENGTH(v._Comment) * 2 + DATALENGTH(v._Content) AS ReadySize,
		NULL AS RawSize
	FROM
		_DataHistoryMetadata AS md
		INNER JOIN _DataHistoryLatestVersions AS l
		ON md._MetadataId = l._MetadataId
		INNER JOIN _DataHistoryVersions AS v
		ON 0 = 0
			AND v._HistoryDataId = l._HistoryDataId
			AND v._MetadataVersionNumber = md._MetadataVersionNumber
	UNION ALL
	--{Выборка: СырыеВерсии ----------------------------------------
	SELECT
		md._MetadataId AS MetadataId,
		v._DataId AS DataId,
		NULL AS VersionNumber,
		NULL AS Date,
		NULL AS ReadySize,
		100 + DATALENGTH(v._Content) AS RawSize
	FROM
		_DataHistoryMetadata AS md
		INNER JOIN _DataHistoryQueue0 AS v
		ON md._MetadataId = v._MetadataId
		INNER JOIN (
			SELECT
				m._MetadataId AS _MetadataId,
				MAX(m._MetadataVersionNumber) AS _MetadataVersionNumber
			FROM
				_DataHistoryMetadata AS m
			GROUP BY
				m._MetadataId) AS mdmax
		ON 0 = 0
			AND md._MetadataId = mdmax._MetadataId
			AND md._MetadataVersionNumber = mdmax._MetadataVersionNumber) AS q
GROUP BY
	q.MetadataId  
