问题
How can I optimize my SQL code ?
I want to add alias.
I am using SQL Server Compact Edition.
( ... ) is a SELECT
query
SELECT
*
FROM ( ... )
WHERE
id IN
(
SELECT
id
FROM ( ... )
GROUP BY
id
HAVING
COUNT( * ) > 1
)
回答1:
I would suggest to use that query only once. You can create a CTE of that query and then write the query as follows:
with cte
As
(....)
Select *
from cte
where id in
(select id from cte
group by id
having count(*) > 1)
Hope it helps
回答2:
this is another option:
SELECT * FROM
(SELECT *, COUNT(*) OVER(PARTITION BY id) ids FROM (...)) x
WHERE ids>1
来源:https://stackoverflow.com/questions/23406467/t-sql-sql-server-compact-edition-alias-for-select