2017-02-02 84 views
3

這可能是一個愚蠢的問題,但我不能算出這個 我有這樣的查詢:我可以將select語句中的select變成自加入嗎?

select TERM_SID 
,max(PUBLICDATA) as PublicData 
,max(PUBLIC_AGGREGATE) as Public_AGGregate 
,max(INTERNAL) as Internal 
,max(INTERNAL_AGGREGATE) as internal_Aggregate 
,max(LIMITED) as Limited 
,max(RESTRICTED) as Restricted 
from 
(
     SELECT TERM_SID, 
     CASE WHEN d2.DATA_CLASSIFICATION_DESC='Public data' THEN 'Y' ELSE 'N' END AS 'PUBLICDATA', 
     CASE WHEN d2.DATA_CLASSIFICATION_DESC='Public data in aggregate' THEN 'Y' ELSE 'N' END as 'PUBLIC_AGGREGATE', 
     CASE WHEN d2.DATA_CLASSIFICATION_DESC='Internal data' THEN 'Y' ELSE 'N' END as 'INTERNAL', 
     CASE WHEN d2.DATA_CLASSIFICATION_DESC='Internal data in aggregate' THEN 'Y' ELSE 'N' END as 'INTERNAL_AGGREGATE', 
     CASE WHEN d2.DATA_CLASSIFICATION_DESC='Limited data' THEN 'Y' ELSE 'N' END as 'LIMITED', 
     CASE WHEN d2.DATA_CLASSIFICATION_DESC='Restricted data' THEN 'Y' ELSE 'N' END as 'RESTRICTED' 
     FROM [UDW_DATA_DICTIONARY].[dbo].[DATA_CLASSIFICATION] d2 
     JOIN [UDW_DATA_DICTIONARY].[dbo].[DATA_CLASSIFICATION_MAPPING] dm2 ON dm2.DATA_CLASSIFICATION_SID=d2.DATA_CLASSIFICATION_SID 
) mat 
group by Term_SID 

,我曾試圖把它轉換,但我一直在內部選擇的加盟得到絆倒了,是有一種方法可以通過連接重新構建以提高性能。

回答

2

把它變成使用Common Table Expression(CTE)派生表和可以參考它,就好像它是任何其它表:

with mat as 
(
     SELECT TERM_SID 
      ,CASE WHEN d2.DATA_CLASSIFICATION_DESC = 'Public data' THEN 'Y' ELSE 'N' END AS PUBLICDATA 
      ,CASE WHEN d2.DATA_CLASSIFICATION_DESC = 'Public data in aggregate' THEN 'Y' ELSE 'N' END as PUBLIC_AGGREGATE 
      ,CASE WHEN d2.DATA_CLASSIFICATION_DESC = 'Internal data' THEN 'Y' ELSE 'N' END as INTERNAL 
      ,CASE WHEN d2.DATA_CLASSIFICATION_DESC = 'Internal data in aggregate' THEN 'Y' ELSE 'N' END as INTERNAL_AGGREGATE 
      ,CASE WHEN d2.DATA_CLASSIFICATION_DESC = 'Limited data' THEN 'Y' ELSE 'N' END as LIMITED 
      ,CASE WHEN d2.DATA_CLASSIFICATION_DESC = 'Restricted data' THEN 'Y' ELSE 'N' END as RESTRICTED 
     FROM [UDW_DATA_DICTIONARY].[dbo].[DATA_CLASSIFICATION] d2 
      JOIN [UDW_DATA_DICTIONARY].[dbo].[DATA_CLASSIFICATION_MAPPING] dm2 
       ON dm2.DATA_CLASSIFICATION_SID = d2.DATA_CLASSIFICATION_SID 
) 
select m1.TERM_SID 
     ,m1.max(PUBLICDATA) as PublicData 
     ,m1.max(PUBLIC_AGGREGATE) as Public_AGGregate 
     ,m1.max(INTERNAL) as Internal 
     ,m1.max(INTERNAL_AGGREGATE) as internal_Aggregate 
     ,m1.max(LIMITED) as Limited 
     ,m1.max(RESTRICTED) as Restricted 

     ,m2.count(1) as mat2count 
from mat m1 
    left join mat m2 
     on(m1.TERM_SID = m2.TERM_SID) 
group by Term_SID