2012-03-07 78 views
1

的我在SSRS,需要做出一個圖表2年的數據進行比較的圖表。由於ssrs中的圖表只能使用數據列來存儲值,而不能使用行,所以我不得不寫很長的包含很多聯合的查詢。我需要12個月的橫軸,我不能創建一個新的表格或任何用戶定義的功能。一切都必須在一個查詢中。 有沒有更簡單的方法來完成這項任務?SQL Server Reporting Services圖表查詢。如何擺脫工會

SELECT 
'01' AS 'MONTH', 
(SELECT COUNT(*) FROM Order JOIN Car ON Order.Car_ID = Car.ID JOIN CarType ON Car.CarType_ID = CarType.ID WHERE @Year = YEAR(Order.OrderDate) AND (@GPI IS NULL OR @GPI = CarType.GPI) AND (@CarType_ID IS NULL OR @CarType_ID = CarType.ID) AND '01' = MONTH(Order.OrderDate)) AS 'Orders1', 
(SELECT COUNT(*) FROM Order JOIN Car ON Order.Car_ID = Car.ID JOIN CarType ON Car.CarType_ID = CarType.ID WHERE @Year -1 = YEAR(Order.OrderDate) AND (@GPI IS NULL OR @GPI = CarType.GPI) AND (@CarType_ID IS NULL OR @CarType_ID = CarType.ID) AND '01' = MONTH(Order.OrderDate)) AS 'Orders2' 
UNION 
SELECT 
'02' AS 'MONTH', 
(SELECT COUNT(*) FROM Order JOIN Car ON Order.Car_ID = Car.ID JOIN CarType ON Car.CarType_ID = CarType.ID WHERE @Year = YEAR(Order.OrderDate) AND (@GPI IS NULL OR @GPI = CarType.GPI) AND (@CarType_ID IS NULL OR @CarType_ID = CarType.ID) AND '02' = MONTH(Order.OrderDate)) AS 'Orders1', 
(SELECT COUNT(*) FROM Order JOIN Car ON Order.Car_ID = Car.ID JOIN CarType ON Car.CarType_ID = CarType.ID WHERE @Year -1 = YEAR(Order.OrderDate) AND (@GPI IS NULL OR @GPI = CarType.GPI) AND (@CarType_ID IS NULL OR @CarType_ID = CarType.ID) AND '02' = MONTH(Order.OrderDate)) AS 'Orders2' 

--It goes on for 12 months 

回答

3

嘗試:

select MONTH(Order.OrderDate) as [MONTH], 
     COUNT(CASE WHEN @Year = YEAR(Order.OrderDate) THEN 1 END) as [Orders1], 
     COUNT(CASE WHEN @Year-1 = YEAR(Order.OrderDate) THEN 1 END) as [Orders2] 
from Order 
JOIN Car ON Order.Car_ID = Car.ID 
JOIN CarType ONCar.CarType_ID = CarType.ID 
WHERE (@GPI IS NULL OR @GPI = CarType.GPI) AND 
     (@CarType_ID IS NULL OR @CarType_ID = CarType.ID) 
group by MONTH(Order.OrderDate) 
+0

謝謝!這很棒! – Beninja2 2012-03-07 16:06:54

0

您可以通過每個月份1-12在存儲過程和循環這個CURSOR做,你只是這出SELECT聲明與SELECT聲明。

CREATE PROCEDURE [dbo].[test] 
AS 
BEGIN 
    SET NOCOUNT ON; 

    CREATE TABLE #temp 
    (
     [Month]  int 
     , Orders1 int 
     , Orders2 int 
    ) 

    DECLARE @MonthCount int 
    SET @MonthCount = 1   

    WHILE @MonthCount <= 12 
     BEGIN 
     INSERT INTO #temp 
     SELECT @MonthCount, (@MonthCount + 1) as Orders1, (@MonthCount + 2) as Orders2  

     SET @MonthCount = @MonthCount + 1 
     END 

    SELECT [Month], Orders1, Orders2 
    FROM #temp 

    DROP TABLE #temp 
END 

這會將數據加載到臨時表中,該過程完成後會被刪除。

+0

我們可能會改變我們的數據庫到數據倉庫最終,所以我試圖避免存儲過程來讓事情變得簡單。 – Beninja2 2012-03-07 16:06:24