非常感谢您的帮助
格里
如何使用LAVG和患者数月。实施例
Facility Jan Feb Mar ect
Downey 30 25 28
Downey 10 9 8
我知道这不起作用,但这就是我要做的事情
PIVOT(SUM(LAVG),计数(患者)FOR IN月(jan,feb,mar 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 :(得分:0)
正如您所提到的,您在枢轴内不能有两个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
注意:要区分Sum
和Count
我使用了额外的列Aggregate