2014-12-25 92 views
0

感謝您的幫助樞軸上的兩個總場

格里

如何在LAVG轉動和患者換了個喜。例如

Facility Jan Feb Mar ect 

Downey 30 25 28 

Downey 10 9 8 

我知道這不工作,但是這是我做什麼

PIVOT(SUM(LAVG),伯爵(病人)總額(一月,二月,三月ECT個月

ALTER PROCEDURE [dbo].[Spoclos] 
    -- Add the parameters for the stored procedure here 
    @Year  INT, 
    @PayerCode VARCHAR(3), 
    @ID  INT 
AS 
    BEGIN 
     -- SET NOCOUNT ON added to prevent extra result sets from 
     -- interfering with SELECT statements. 
     SET NOCOUNT ON; 

     -- Insert statements for procedure here 
     SELECT * 
     FROM (SELECT LEFT(Months, 3) AS Months, 
        FacilityName, 
        LAVG, 
        Patient, 
        Region, 
        ID, 
        payercode, 
        facilityCode 
       FROM dbo.LOSGroup 
       WHERE PayerCode = @PayerCode 
        AND years = @year 
        AND ID = @id) AS s 
      PIVOT (Sum(LAVG) 
        FOR months IN (jan,feb,mar,apr, 
         may,jun,jul,aug, 
         sep,oct,nov,dec)) AS piv 
     ORDER BY ID 
    END 
+0

什麼SQL變種是什麼? – Jasen

+0

因爲語法看起來像sql server,所以我正在標記'Sql Server' –

回答

0

至於你提到你不能有內轉動2種Aggregate功能。

有兩個單獨的Pivot查詢一個找到Sum和另一個找到Count。然後使用Union All合併結果。

SELECT 'Sum' [Aggregate],* 
FROM (SELECT LEFT(Months, 3) AS Months, 
       FacilityName,LAVG,Patient, 
       Region,ID,payercode, 
       facilityCode 
     FROM dbo.LOSGroup 
     WHERE PayerCode = @PayerCode 
       AND years = @year 
       AND ID = @id) AS s 
     PIVOT (Sum(LAVG) 
      FOR months IN (jan,feb,mar,apr, 
          may,jun,jul,aug, 
          sep,oct,nov,dec)) AS piv 
UNION ALL 
SELECT 'Count' [Aggregate],* 
FROM (SELECT LEFT(Months, 3) AS Months, 
       FacilityName,LAVG,Patient, 
       Region,ID,payercode, 
       facilityCode 
     FROM dbo.LOSGroup 
     WHERE PayerCode = @PayerCode 
       AND years = @year 
       AND ID = @id) AS s 
     PIVOT (Count(LAVG) 
      FOR months IN (jan,feb,mar,apr, 
          may,jun,jul,aug, 
          sep,oct,nov,dec)) AS piv 
ORDER BY ID 

注:爲了區分SumCount我使用了一個額外的列Aggregate