2017-08-13 151 views
-1

使用AdventureWorks2008R2SQL獲得總訂單從CTE聲明

我:

With CTE As 
( 
Select 2005 As [Year] 
Union 
Select 2006 
Union 
Select 2007 
Union 
Select 2008 
) 
Select * From CTE 

這會給我的年(行)二〇〇四年至2008年:

2005 
2006 
2007 
2008 

現在,我要將每年的總訂單插入到這些行中。

將下面的代碼給我訂單總額:

WITH CTE 
AS 
(
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS [Year] 
    FROM Sales.SalesOrderHeader 
) 
SELECT COUNT(SalesOrderID) AS TotalOrders 
FROM CTE 
GROUP BY [Year] 

我應該如何編寫它(像INSERT INTO)?

enter image description here

+1

爲什麼在按年份(訂單日期)做簡單分組時會使用cte? BTW不應該被標記爲sqlserver? –

+0

這種情況下你不應該使用CTE。它不必要地更復雜和更常見的捷徑。如果有人遇到這段代碼,他會查找你的意思和遞歸隱藏的地方。 – Deadsheep39

回答

0

你可以使用:

WITH cte AS 
( 
    Select 2005 AS [Year] UNION 
    Select 2006 UNION 
    Select 2007 UNION 
    Select 2008 
) 
SELECT c.[Year], COUNT(soh.*) AS TotalOrders 
FROM cte c 
LEFT JOIN Sales.SalesOrderHeader soh 
    ON c.[Year] = YEAR(soh.OrderDate) 
GROUP BY c.[Year] 
ORDER BY c.[Year]; 

如果您確信每年有數據使用簡單:

SELECT YEAR(soh.OrderDate), COUNT(*) AS TotalOrders 
FROM Sales.SalesOrderHeader soh 
WHERE soh.OrderDate >= '20050101' AND soh.OrderData < '20090101' 
GROUP BY YEAR(soh.OrderDate) 
ORDER BY YEAR(soh.OrderDate); 
0

試試這個:

insert into table(col1,col2) 
SELECT year,COUNT(SalesOrderID) AS TotalOrders 
FROM (
SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS [Year] 
    FROM Sales.SalesOrderHeader) as t1 
GROUP BY Year 
0
INSERT INTO table_name (year_col,total_order_col) 
SELECT YEAR(OrderDate) AS [Year] ,COUNT(1) AS Total_Orders 
FROM Sales.SalesOrderHeader 
GROUP BY YEAR(OrderDate)