我有以下查询生成我的透视结果:
SELECT * FROM
(
SELECT
#tmp1.Name,
DATEDIFF(D,#tmp1.AuthDate,#tmp1.AuthExpirationDate) AS AuthLenInDays,
#tmp1.NbrOfAuthorizations,
#tmp1.MODE
FROM #tmp1
LEFT JOIN #tmp2
ON #tmp2.AuthID = #tmp1.AuthID
GROUP BY #tmp1.Name, #tmp1.NbrOfAuthorizations, #tmp1.AuthDate, #tmp1.AuthExpirationDate, #tmp1.MODE
) AS InnerTbl
PIVOT
(AVG(AuthLenInDays) FOR [MODE] IN ([Preservation])
) PivotResults1
结果如下:
Name NbrOfAuthorizations Preservation
Centro 1 79
Dennis 1 92
Therapy Center 1 68
Florez 1 92
我有两个问题,我无法弄清楚,我已经尝试了我能想到的一切,甚至还有来自stackoverflow的其他建议。
如果我获取原始数据并将其导出为excel并在那里进行转移,我可以看到数字和我应该得到的数据。我试图采取这个过程,纯粹在SQL中完成。根据表中的数据,SUM的值应为
Name NbrOfAuthorizations Preservation
Centro 5 79
Dennis 1 92
Therapy Center 57 68
Florez 1 92
那里有任何枢轴大师吗?
答案 0 :(得分:1)
看起来根本不需要支点:
select
t1.Name,
sum(t1.NbrOfAuthorizations) as NbrOfAuthorizations,
avg(datediff(dd, t1.AuthDate, t1.AuthExpirationDate)) as AuthLenInDays
from #tmp1 as t1
-- looks like you don't need join also, or there're multiple rows
-- in #tmp2 for row in #tmp1
-- left outer join #tmp2 as t2 on t2.AuthID = t1.AuthID
where t1.mode = 'Preservation'
group by t1.Name