1

我正在使用 SQL Server 2008 R2。我有六个表,我从中获取许多按创建日期分组的行。

例如 :

SELECT COUNT(*) AS NoOfReading FROM TableA
WHERE IsDeleted = 0 
GROUP BY CONVERT(VARCHAR(10), CreatedDtUTC,111)

SELECT COUNT(*) AS NoOfReading FROM TableB
WHERE IsDeleted = 0 
GROUP BY CONVERT(VARCHAR(10), CreatedDtUTC,111)

SELECT COUNT(*) AS NoOfReading FROM TableC
WHERE IsDeleted = 0 
GROUP BY CONVERT(VARCHAR(10), CreatedDtUTC,111)

及以后..

现在我想sum of NoOfReading按创建日期从所有表中分组。有什么解决办法??

PS:我尝试在所有查询之间使用“+”但给出错误。

谢谢

4

3 回答 3

0

我认为一个简单的添加可以工作..

select (
    (SELECT COUNT(*) FROM TableA
    WHERE IsDeleted = 0 
    GROUP BY CONVERT(VARCHAR(10), CreatedDtUTC,111))
    +
    (SELECT COUNT(*) FROM TableB
    WHERE IsDeleted = 0 
    GROUP BY CONVERT(VARCHAR(10), CreatedDtUTC,111))
    +
    (SELECT COUNT(*) FROM TableC
    WHERE IsDeleted = 0 
    GROUP BY CONVERT(VARCHAR(10), CreatedDtUTC,111))
    )  AS NoOfReadingSum
于 2013-04-09T06:34:15.660 回答
0

Resolved it my self :

;WITH MeasurementReadings(NoOfReading, CreatedDtUTC) AS 
(
    SELECT COUNT(*) AS  NoOfReading, CreatedDtUTC FROM TableA
    WHERE IsDeleted = 0 
    GROUP BY CONVERT(VARCHAR(10), CreatedDtUTC,111)
    UNION ALL
    SELECT COUNT(*) AS  NoOfReading, CreatedDtUTC  FROM TableB
    WHERE IsDeleted = 0 
    GROUP BY CONVERT(VARCHAR(10), CreatedDtUTC,111)
    UNION ALL
    SELECT COUNT(*) AS  NoOfReading, CreatedDtUTC FROM TableC
    WHERE IsDeleted = 0 
    GROUP BY CONVERT(VARCHAR(10), CreatedDtUTC,111)
)  
SELECT SUM(NoOfReading) AS NoOfRecords, CreatedDtUTC 
FROM MeasurementReadings
GROUP BY CreatedDtUTC

Thanks

于 2013-04-09T06:42:44.810 回答
0

您可以使用UNION ALLwhich 保留重复项:

SELECT COUNT(*) AS NoOfReading FROM
(
   SELECT CreatedDtUTC,IsDeleted FROM TableA
   UNION ALL
   SELECT CreatedDtUTC,IsDeleted FROM TableB
   UNION ALL
   SELECT CreatedDtUTC,IsDeleted FROM TableC
) t
WHERE IsDeleted = 0 
GROUP BY DATEADD(day,DATEDIFF(day,0,CreatedDtUTC),0)
于 2013-04-09T06:39:36.460 回答