也許這將幫助
DECLARE @DateStart DATETIME, @DateEnd DATETIME;
SET @DateStart = CONVERT(DATETIME, '1/1/2013 12:00:00 AM');
SET @DateEnd = CONVERT(DATETIME, '12/31/2013 12:00:00 AM');
SELECT
MONTH(o.OrderDate) [Month]
, YEAR(o.OrderDate) [Year]
, ISNULL(C.CustomerType,0) [CustomerType]
, COUNT(o.Total) [NoOfCustomer]
FROM Orders o
LEFT OUTER JOIN Customers C on C.CustomerID = o.CustomerID
WHERE o.OrderDate BETWEEN @DateStart AND @DateEnd
GROUP BY MONTH(o.OrderDate), YEAR(o.OrderDate), ISNULL(C.CustomerType,0)
ORDER BY [Year],[Month],[CustomerType];
UPDATE
DECLARE @DateStart DATETIME, @DateEnd DATETIME;
DECLARE @CustTypeTable TABLE(CustomerType INT);
DECLARE @i INT = 0;
/*Create table variable for customer types*/
WHILE @i < 5
BEGIN
INSERT INTO @CustTypeTable
SELECT @i
SET @i = @i + 1
END
/*The statement will force all CustomerTypes with a "fake" table*/
DECLARE @StagingTable TABLE([Month] INT, [Year] INT, CustomerType INT)
INSERT INTO @StagingTable
SELECT
MONTH(o.OrderDate) [Month]
, YEAR(o.OrderDate) [Year]
, T.CustomerType
FROM Orders o
CROSS JOIN @CustTypeTable T
GROUP BY MONTH(o.OrderDate), YEAR(o.OrderDate), T.CustomerType
SET @DateStart = CONVERT(DATETIME, '1/1/2013 12:00:00 AM');
SET @DateEnd = CONVERT(DATETIME, '12/31/2013 12:00:00 AM');
/*Create another staging table for results*/
DECLARE @StagingTable2 TABLE([Month] INT, [Year] INT, CustomerType INT, [NoOfCustomer] BIGINT)
INSERT INTO @StagingTable2
SELECT
MONTH(o.OrderDate) [Month]
, YEAR(o.OrderDate) [Year]
, C.CustomerType [CustomerType]
, COUNT(o.Total) [NoOfCustomer]
FROM Orders o
LEFT OUTER JOIN Customers C on C.CustomerID = o.CustomerID
WHERE o.OrderDate BETWEEN @DateStart AND @DateEnd
GROUP BY MONTH(o.OrderDate), YEAR(o.OrderDate), C.CustomerType
ORDER BY [Year],[Month],[CustomerType];
/*Now lets join them up*/
SELECT
T1.Year
, T1.Month
, T1.CustomerType
, T2.[NoOfCustomer]
FROM @StagingTable T1
LEFT OUTER JOIN @StagingTable2 T2 ON T2.Year = T1.Year AND T2.Month = T1.Month AND T2.CustomerType = T1.CustomerType
大約相當於這就是我能爲你做
你與查詢 – Armand
從我看到你應該子句添加客戶類型進行分組太 – Raphael