我正在將現有的工作查詢從MySQL移動到MS SQL Server(版本11),我無法轉換在MySQL上正常工作的查詢之一。如何從SQL Server表中選擇不同的行
它基本上只考慮4列值從表中選擇不同的行。
表是(有數據的最小的子集,同一類型的數據存在於不同的名稱,sub_name和用戶):
+-------+-------+-------+-------+-----------------+----------+--------+
| col_1 | col_2 | col_3 | col_4 | name | sub_name | user |
+-------+-------+-------+-------+-----------------+----------+--------+
| 50 | 40 | 20 | 30 | one_four_eleven | One | user_1 |
| 50 | 40 | 20 | 30 | one_four_eleven | Two | user_1 |
| 50 | 40 | 20 | 30 | one_four_eleven | Three | user_1 |
| 50 | 40 | 20 | 30 | one_four_eleven | Four | user_1 |
| 50 | 40 | 20 | 30 | one_four_eleven | Five | user_1 |
| 50 | 40 | 20 | 30 | one_four_eleven | Six | user_1 |
| 50 | 40 | 20 | 30 | one_four_eleven | Seven | user_1 |
| 50 | 40 | 20 | 30 | one_four_eleven | Eight | user_1 |
| 50 | 40 | 20 | 30 | one_four_eleven | Nine | user_1 |
| 50 | 40 | 15 | 30 | one_four_eleven | Ten | user_1 |
+-------+-------+-------+-------+-----------------+----------+--------+
而我需要的是,如果所有COL_1,COL_2,col_3和col_4與其他行相比,在一行中具有相同的值,那麼應該只選擇其中一個相同的行。
由於在給定的數據中,只有最後一行在col_3中有不同的數據,所以結果應該只有兩行。一行在col_1,col_2,col_3,col_4和名稱中顯示相同的值。第二行應該是最後一行。
我能夠做到這一點使用MySQL查詢如下圖所示,它的結果是:
mysql> SELECT DISTINCT col_1, col_2, col_3, col_4, name FROM table_name
WHERE (user = 'user_1' OR user = 'GLOBAL') AND name = 'one_four_eleven' AND sub_name != 'ALL' GROUP BY sub_name;
+-------+-------+-------+-------+-----------------+
| col_1 | col_2 | col_3 | col_4 | name |
+-------+-------+-------+-------+-----------------+
| 50 | 40 | 20 | 30 | one_four_eleven |
| 50 | 40 | 15 | 30 | one_four_eleven |
+-------+-------+-------+-------+-----------------+
但是,當我試圖此查詢轉換爲MS SQL Server上運行,它給錯誤:
Column 'table_name.col_1' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
如何爲SQL Server編寫查詢,該查詢會得到與上述MySQL查詢相同的結果。
由於您已經在執行'DISTINCT',因此只需刪除您的'GROUP BY sub_name'語句,它應該按照您的預期工作。 – tweray