0

我想按日期计算表 8 表中的数据并将其结果为一张表

______|| table 1 || table 2 || table 3 || table 4 ||
date1 || 7,000   || 8,000   || 9,000   || 10,000  ||  
date1 || 7,000   || 8,000   || 9,000   || 10,000  ||  
4

1 回答 1

0

如果您在 SQL Server 中:

;With Table1CTE AS
(
    SELECT CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112)) AS Date1,
           COUNT(*) AS Table1
    FROM   Table1
    GROUP BY CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112))
)
,Table2CTE AS
(
    SELECT CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112)) AS Date1,
           COUNT(*) AS Table2
    FROM   Table2
    GROUP BY CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112))
)
,Table3CTE AS
(
    SELECT CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112)) AS Date1,
           COUNT(*) AS Table3
    FROM   Table3
    GROUP BY CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112))
)
,Table4CTE AS
(
    SELECT CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112)) AS Date1,
           COUNT(*) AS Table4
    FROM   Table4
    GROUP BY CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112))
)
SELECT Date1,
       Table1,
       Table2,
       Table3,
       Table4
FROM   Table1CTE T1
       FULL OUTER JOIN Table2CTE T2
            ON T1.date1 = T2.date1
       FULL OUTER JOIN Table3CTE T3
            ON T1.date1 = T3.date1
       FULL OUTER JOIN Table4CTE T4
            ON T1.date1 = T4.date1

我正在使用FULL OUTER JOIN,因为我不知道所有日期是否都存在于所有表格中。

您可以随时尝试加入子查询:

SELECT Date1,
       Table1,
       Table2,
       Table3,
       Table4
FROM   (
           SELECT CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112)) AS Date1,
                  COUNT(*) AS Table1
           FROM   Table1
           GROUP BY CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112))
       ) T1
       FULL OUTER JOIN 
       (
           SELECT CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112)) AS Date1,
                  COUNT(*) AS Table2
           FROM   Table2
           GROUP BY CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112))
       ) T2
            ON T1.date1 = T2.date1
       FULL OUTER JOIN 
       (
           SELECT CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112)) AS Date1,
                  COUNT(*) AS Table3
           FROM   Table3
           GROUP BY CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112))
       ) T3
            ON T1.date1 = T3.date1
       FULL OUTER JOIN 
       (
           SELECT CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112)) AS Date1,
                  COUNT(*) AS Table4
           FROM   Table4
           GROUP BY CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112))
       ) T4
            ON T1.date1 = T4.date1
于 2013-10-01T06:54:23.193 回答