I was hoping to run a single query and get results from that. However, MSSQL complains about a syntax error near the GROUP
key word.
I was hoping to do the following.
SELECT COUNT(*) AS cnt,Field_2
FROM (SELECT DISTINCT Field_1, Field_2
FROM Table_1)
GROUP BY Field_2
HAVING COUNT(*) > 1
Instead I had to create a view, View_1, with the query
SELECT DISTINCT Field_1, Field_2
FROM Table_1
And then do a
SELECT COUNT(*) AS cnt, Field_2
FROM View_1
GROUP BY Field_2
HAVING COUNT(*) > 1
The question is why, to my mind it is essentially the same SQL.
Note: Field, table and view names have been changed to protect the innocent. ;-)
Subqueries cannot be used in the FROM clause of a view. There is a general principle that you cannot modify a table and select from the same table in a subquery.
1 Answer. The SELECT statement doesn't contain a subquery in the FROM clause.
SQL Server requires you to specify a table alias for a derived table/inline view:
SELECT COUNT(*) AS cnt,
x.Field_2
FROM (SELECT DISTINCT Field_1, Field_2
FROM Table_1) AS x
GROUP BY x.Field_2
HAVING COUNT(*) > 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With