将复杂的oracle查询转换为sql server

时间:2017-06-19 14:12:54

标签: sql-server oracle

我正在尝试将复杂的Oracle SQL查询转换为SQL Server SQL。这是我要翻译的查询:

SELECT  TABLE_A.COL_ID, TABLE_A.COL2_ID, TABLE_A.COL3_ID, COL4, COL5, COL6, alias.COL7, alias.COL8 
FROM  TABLE_A 
Inner Join 
(SELECT  UNIQUE TABLE_A.COL_ID, LISTAGG(TABLE_B.COL4_ID, ',') 
WITHIN GROUP (ORDER BY TABLE_A.COL_ID) COL7, LISTAGG(TABLE_C.COL5_ID, ',') 
WITHIN GROUP (ORDER BY TABLE_A.COL_ID) COL8 
FROM  TABLE_A Left Join TABLE_B 
on TABLE_A.COL_ID = TABLE_B.COL_ID 
Left Join TABLE_C on TABLE_A.COL_ID = TABLE_C.COL_ID  
GROUP BY TABLE_A.COL_ID 
HAVING (LISTAGG(TABLE_B.COL4_ID) 
WITHIN GROUP (ORDER BY TABLE_A.COL_ID)) is not null OR (LISTAGG(TABLE_C.COL5_ID) 
WITHIN GROUP (ORDER BY TABLE_A.COL_ID)) is not null ) alias on TABLE_A.COL_ID = alias.COL_ID 
Left Join TABLE_D on TABLE_D.COL2_ID = TABLE_A.COL2_ID 
Left Join TABLE_E on TABLE_E.COL3_ID = TABLE_A.COL3_ID 
Left Join (SELECT DISTINCT COL_ID As idCol FROM  TABLE_F 
WHERE (TABLE_F.COL6_ID = 363) ) aliasCol on TABLE_E.COL_ID = aliasCol.idCol 
ORDER BY COL_ID ASC; 

这是我到目前为止所做的:

use MY_DB;

WITH auxTable AS
	(SELECT dbo.TABLE_A.COL_ID, dbo.TABLE_B.COL4_ID, dbo.TABLE_C.COL5_ID FROM  dbo.TABLE_A 
		Left Join dbo.TABLE_B on dbo.TABLE_A.COL_ID = dbo.TABLE_B.COL_ID 
		Left Join dbo.TABLE_C on dbo.TABLE_A.COL_ID = dbo.TABLE_C.COL_ID )

SELECT  dbo.TABLE_A.COL_ID, dbo.TABLE_A.COL2_ID, dbo.TABLE_A.COL3_ID, COL4, COL5, COL6, alias.COL7, alias.COL8 
FROM  dbo.TABLE_A 
Inner Join 

(SELECT  DISTINCT COL_ID, STUFF(( SELECT  ','+ CAST(COL4_ID AS VARCHAR(MAX)) FROM auxTable a WHERE b.COL_ID = a.COL_ID FOR XML PATH('')),1 ,1, '')  COL7,
 STUFF(( SELECT  ','+ CAST(COL5_ID AS VARCHAR(MAX)) FROM auxTable a WHERE b.COL_ID = a.COL_ID FOR XML PATH('')),1 ,1, '') COL8 
FROM  auxTable b
GROUP BY COL_ID HAVING (STUFF(( SELECT  CAST(COL4_ID AS VARCHAR(MAX)) FROM auxTable a WHERE b.COL_ID = a.COL_ID FOR XML PATH('')),1 ,1, '')) is not null 
OR (STUFF(( SELECT  CAST(COL4_ID AS VARCHAR(MAX)) FROM auxTable a WHERE b.COL_ID = a.COL_ID FOR XML PATH('')),1 ,1, '')) is not null ) alias 
on dbo.TABLE_A.COL_ID = alias.COL_ID Left Join dbo.TABLE_D on dbo.TABLE_D.COL2_ID = dbo.TABLE_A.COL2_ID 
Left Join dbo.TABLE_E on dbo.TABLE_E.COL3_ID = dbo.TABLE_A.COL3_ID Left Join (SELECT DISTINCT COL_ID As idCol FROM  dbo.TABLE_F 
WHERE (dbo.TABLE_F.COL6_ID = 363) ) aliasCol on dbo.TABLE_E.COL_ID = aliasCol.idCol ORDER BY COL4 ASC;

我在两个查询中获得的结果几乎相同,但我在Oracle中获得了16行,在SQL Server中只获得了12行,我无法理解为什么。

0 个答案:

没有答案