2013-10-01 100 views
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 || 
+0

我的意思是,我有8臺數。抱歉不清楚 – Anue

+0

請檢查您的問題,因爲它不清楚。另外,我沒有看到表8? – user172839

回答

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 
+0

for date1我有這樣的數據'2011-02-09 20:25:42.000' 並且結果不是日復一日的組 我該如何處理這個問題,請再次幫助我。 – Anue

+0

@Anue'CONVERT(DATETIME,CONVERT(VARCHAR,Date1,112))'會讓你獲得Date1的日期部分。我希望我的問題得到了解決...... –

+0

確定它現在正在工作,我將使用並測試一段時間 – Anue

相關問題