SQL从CTE语句获取总订单

时间:2017-08-13 08:03:03

标签: sql-server tsql insert sql-order-by common-table-expression

使用AdventureWorks2008R2

我有:

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

这将给我2004年至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)?

enter image description here

3 个答案:

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

答案 1 :(得分:0)

试试这个:

{{1}}

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