SELECT
Col1+CASE WHEN EXISTS(SELECT 1 FROM Table2 T2 where T2.ID=Col1 AND T2.Initial='B')
THEN '*' ELSE ''END ,
Col2+CASE WHEN EXISTS(SELECT 1 FROM Table2 T2 where T2.ID=Col2 AND T2.Initial='B')
THEN '*' ELSE ''END ,
Col3+CASE WHEN EXISTS(SELECT 1 FROM Table2 T2 where T2.ID=Col3 AND T2.Initial='B')
THEN '*' ELSE ''END
FROM Table1
GROUP BY Col1, Col2,Col3
ORDER BY Col1,Col2,Col3
有没有办法用更优化的方法编写上述查询以获得相同的结果?
答案 0 :(得分:1)
你应该和你一样,所以我不确定它可能会有多优化。或许更具可读性:
SELECT
Col1+CASE WHEN T2.ID is not null THEN '*' ELSE ''END ,
Col2+CASE WHEN T3.ID is not null THEN '*' ELSE ''END ,
Col3+CASE WHEN T4.ID is not null THEN '*' ELSE ''END
FROM
Table1 T1
LEFT JOIN Table2 T2 on T2.ID=T1.Col1 AND T2.Initial='B'
LEFT JOIN Table2 T3 on T3.ID=T1.Col2 AND T3.Initial='B'
LEFT JOIN Table2 T4 on T4.ID=T1.Col3 AND T4.Initial='B'
GROUP BY T1.Col1,T1.Col2,T1.Col3
ORDER BY T1.Col1,T1.Col2,T1.Col3