WITH cte
AS (
SELECT a.related_serial_number
,a.serial_number
,b.role_id
,c.role_name
,D.Customer_Name
,b.cmat_customer_id
,b.CMAT_site_id
,f.system_status
,f.orgnl_sales_order_number
,a.creation_date
,a.instance_relationship_id
FROM eim_instance_relationships a
,eim.EIM_LATEST_SYS_PARTY_ROLE b
,eim.EIM_Roles c
,eim.EIM_Party D
,EIM.EIM_System f
WHERE a.Pkey BETWEEN '31'
AND '45'
AND a.p_pkey BETWEEN '1'
AND '2'
AND A.serial_number = b.system_serial_number
AND D.cmat_customer_id = b.cmat_customer_id
AND A.serial_number = f.system_serial_number
AND b.role_id = c.role_id
AND related_serial_number = '01c33679-a5b2-11e4-82f6-123478563412'
AND b.role_id IN ('1', '4', '10', '3', '19')
AND a.related_component_type = 'CLUSTER'
AND a.component_type = 'CONTROLLER'
AND a.related_serial_number IN (
SELECT related_serial_number
FROM eim.eim_instance_relationships e
WHERE e.related_component_type = 'CLUSTER'
AND e.component_type = 'CONTROLLER'
AND e.p_pkey BETWEEN '1'
AND '2'
AND e.Pkey BETWEEN '31'
AND '45'
GROUP BY e.related_serial_number
HAVING count(*) > 1
)
ORDER BY 1
,2
)
,cte2
AS (
SELECT row_number() OVER (
PARTITION BY role_name
,cmat_site_id ORDER BY instance_relationship_id DESC
) r
,instance_relationship_id
,related_serial_number
,serial_number
,role_id
,role_name
,Customer_Name
,cmat_customer_id
,CMAT_site_id
,system_status
,orgnl_sales_order_number
,creation_date
FROM cte
WHERE (
related_serial_number
,role_name
) IN (
SELECT related_serial_number
,role_name
FROM (
SELECT related_serial_number
,role_name
,count(*)
FROM (
SELECT related_serial_number
,serial_number
,role_id
,role_name
,customer_name
,CMAT_Customer_ID
,cmat_site_id
,system_status
,orgnl_sales_order_number
,count(*)
FROM cte
GROUP BY related_serial_number
,serial_number
,role_id
,role_name
,customer_name
,CMAT_Customer_ID
,cmat_site_id
,system_status
,orgnl_sales_order_number
)
GROUP BY related_serial_number
,role_name
HAVING COUNT(DISTINCT CMAT_Site_ID) > 1
)
)
)
SELECT *
FROM cte2
WHERE r = 1
ORDER BY related_serial_number
,serial_number
答案 0 :(得分:0)
大多数建议都是为了提高可读性。
对CTE使用meaninfulll名称。不是cte1,cte2
不要使用a,b,c,d
别名,因为它很难阅读。创建一个更有意义的名字。
您没有外部引用的子查询。你也可以用它们来制作它,以便于阅读。
这是我认为唯一可以改善表现的地方。
另一个group by
内的group by
看起来是不必要的。为什么在内部组中包含这么多字段,然后才将两个字段分组。再看起来应该是他自己的CTE。