记录创建日期的不同表组记录的计数总和

时间:2013-04-09 06:27:12

标签: sql-server sql-server-2008-r2

我正在使用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。任何解决方案??

P.S。 :我尝试在所有查询之间使用“+”但出错。

由于

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以使用保留重复项的UNION ALL

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)

答案 2 :(得分:0)

解决了我自己:

;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

由于