2016-09-29 137 views
1

經過很多工作,我設法創建了一個動態數據透視查詢,並提供了我想要的結果。動態數據透視查詢查看/存儲過程?

現在我需要能夠發送參數並過濾我的查詢。通常我只是創建一個視圖,我可以使用SELECT * FROMWHERE子句使用我的參數進行過濾。我讀過從動態透視查詢創建視圖是不可能的,所以我需要幫助來解決這個問題。

這是我的SQL:

DECLARE @cols AS NVARCHAR(MAX), 
     @query AS NVARCHAR(MAX); 

SET @cols = STUFF((SELECT ',' + QUOTENAME(p.tag) 
        FROM (((ZUS_Monatsreport_Kopf k 
        LEFT JOIN ZUS_Monatsreport_Pos p ON k.Id = p.Id_Kopf) 
        LEFT JOIN ADR_Adressen a ON k.Adresse = a.AdressNrADR) 
        LEFT JOIN ADR_GruppenLink gl ON a.AdressNrADR = gl.AdressNrADR) 
        LEFT JOIN ADR_Gruppen g ON gl.GruppeADR = g.GruppeADR 
        GROUP BY p.Tag 
        ORDER BY p.tag 
        FOR XML PATH (''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') 

SET @query = 'SELECT AdressNrADR,Monat,Id_kopf,Name,Artikel, '+ @cols + ' FROM 
      (
       SELECT a.AdressNrADR,k.monat,p.Id_kopf,a.name + '' ''+ a.vorname as Name,p.Artikel, p.Tag,CASE WHEN CAST(p.wert AS VARCHAR(10)) = '''' THEN CAST(p.Menge AS VARCHAR(10)) ELSE CAST(p.Wert AS VARCHAR(10)) END AS Menge 
       FROM (((ZUS_Monatsreport_Kopf k 
       LEFT JOIN ZUS_Monatsreport_Pos p ON k.Id = p.Id_Kopf) 
       LEFT JOIN ADR_Adressen a ON k.Adresse = a.AdressNrADR) 
       LEFT JOIN ADR_GruppenLink gl ON a.AdressNrADR = gl.AdressNrADR) 
       LEFT JOIN ADR_Gruppen g ON gl.GruppeADR = g.GruppeADR 
      ) x 
      pivot 
      (max(menge) 
       for tag in (' [email protected] +') 
      ) p ' 

execute(@query) 

這是我的結果看起來像:

enter image description here

現在我需要能夠做出選擇的這個SQL身邊,說了示例

SELECT * 
FROM mypivotquery 
WHERE AdressNrADR = 10640 (<-parameter) and Monat = 2 (<-parameter) 

我希望我能解釋我在找什麼對於那你們能幫助我:)

感謝

回答

1

您可以添加其中動態查詢條件,改變你的SET @Query聲明,

SET @query = 'SELECT AdressNrADR,Monat,Id_kopf,Name,Artikel, '+ @cols + ' FROM 
     (
      SELECT a.AdressNrADR,k.monat,p.Id_kopf,a.name + '' ''+ a.vorname as Name,p.Artikel, p.Tag,CASE WHEN CAST(p.wert AS VARCHAR(10)) = '''' THEN CAST(p.Menge AS VARCHAR(10)) ELSE CAST(p.Wert AS VARCHAR(10)) END AS Menge 
      FROM (((ZUS_Monatsreport_Kopf k 
      LEFT JOIN ZUS_Monatsreport_Pos p ON k.Id = p.Id_Kopf) 
      LEFT JOIN ADR_Adressen a ON k.Adresse = a.AdressNrADR) 
      LEFT JOIN ADR_GruppenLink gl ON a.AdressNrADR = gl.AdressNrADR) 
      LEFT JOIN ADR_Gruppen g ON gl.GruppeADR = g.GruppeADR 
      WHERE a.AdressNrADR = 10640 (<-parameter) and Monat = 2 (<-parameter) 
     ) x 
      pivot 
      (max(menge) 
      for tag in (' [email protected] +') 
     ) p '