如何从多个表到一个表中进行选择?

时间:2013-10-01 06:39:46

标签: sql

我想按日期计算表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  ||  

1 个答案:

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