2015-07-21 61 views
0

以下MS訪問SQL查詢中給出:如何在SQL Server中定義查詢TRANSFORM/PIVOT?

PARAMETERS Formulare![Hauptmenü]![Startdatum] DateTime, Formulare![Hauptmenü]![Enddatum] DateTime; 

TRANSFORM Count(ds.Datum) AS AnzahlDatum 

SELECT ds.quote_rate 
FROM ds 
GROUP BY ds.quote_rate 
ORDER BY ds.quote_rate DESC , ds.isin 
PIVOT ds.isin; 

我想上面的代碼在SQL Server存儲過程來定義:

CREATE PROCEDURE [dbo].[MonthRepo] 
    -- Add the parameters for the stored procedure here 
    @from datetime, 
    @to datetime 
AS 
BEGIN 
    SET NOCOUNT ON; 

    SELECT * 
    FROM (
     SELECT ds.datum AS DateSum, 
       ds.ct_quot_rate AS Quote, 
       ds.isin 
     FROM ds 
     WHERE ds.datum >= @from AND ds.datum <= @to 
    ) tbl 
    PIVOT (
     ROUND(Quote,0) --Incorrect syntax near '0'. Expecting '.', ID, or QUOTED_ID 
     FOR isin IN(AB000001, AB000002, AB000003) --Incorrect syntax near 'AB000001'. Expecting '(', or SELECT 
    ) piv 
END 

但我發現了錯誤信息,你可以看到代碼中的消息。 PIVOT是有點複雜,我..

表下面你可以看到當輸入日期@from='2015-01-01', @to='2015-01-03'

datum  | quote_rate | isin 
================================== 
2015-01-01 | 100  | AB000001 
2015-01-01 | 100  | AB000002 
2015-01-02 | 98   | AB000003 
2015-01-02 | 70   | AB000001 
2015-01-03 | 100  | AB000001 

這表我想要實現:

quote_rate | AB000001 | AB000002 | AB000003 
=========================================== 
100  |  2 |  1 | 
98   |   |   |  1 
70   |  1 |   | 

編輯:

靜態解決方案:

CREATE PROCEDURE [dbo].[MonthRepo] 
     -- Add the parameters for the stored procedure here 
     @from datetime, 
     @to datetime 
    AS 
    BEGIN 
     SET NOCOUNT ON; 

     SELECT * 
     FROM (
      SELECT ds.datum AS DateSum, 
        ds.ct_quot_rate AS Quote, 
        ds.isin 
      FROM ds 
      WHERE ds.datum >= @from AND ds.datum <= @to 
     ) tbl 
     PIVOT (
      COUNT(Quote) 
      FOR isin IN(AB000001, AB000002, AB000003) 
     ) piv 
    END 

新的問題是,我怎樣才能定義我的靜態代碼爲DYNAMIC查詢?

回答

1

嘗試是這樣的....

SELECT * 
FROM (
    SELECT ds.datum AS DateSum, 
      ROUND(ds.ct_quot_rate,0) AS Quote, 
      ds.isin 
    FROM ds 
    WHERE ds.datum >= @from AND ds.datum <= @to 
) tbl 
PIVOT (
    COUNT(Quote) --Incorrect syntax near '0'. Expecting '.', ID, or QUOTED_ID 
    FOR isin 
    IN(AB000001, AB000002, AB000003) --Incorrect syntax near 'AB000001'. Expecting '(', or SELECT 
) piv 
+0

你能告訴我我該怎麼定義我的靜態代碼,以動態查詢? – yuro