我想按日期來算表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 ||
我想按日期來算表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 ||
如果您是在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
我的意思是,我有8臺數。抱歉不清楚 – Anue
請檢查您的問題,因爲它不清楚。另外,我沒有看到表8? – user172839