且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将具有 GROUP BY 的 MySQL 查询转换为 MSSQL 查询

更新时间:2023-09-14 21:31:58

对于很多数据库,MS SQL Server 就是其中之一,不可能在 GROUP BY 子句中只指定一列,而是对所有数据库使用通配符select 子句中的列.MySQL 在这里很奇怪,它确实允许这样做.

For many databases, and MS SQL Server is one, it is not possible to specify just a single column in the GROUP BY clause, but use the wildcard for all columns in the select clause. MySQL is the odd one here, it does allow this.

所以,信息很简单.您必须在 GROUP BY 子句中指定非聚合列.没有例外.

So, the message is simple. You MUST specify the non-aggregating columns in the GROUP BY clause. No exceptions.

如果您真的只想为每个 tar_owner_id 返回一行,您可能需要考虑使用 ROW_NUMBER() OVER([partition by ...] order by ...).

You might want to consider use of ROW_NUMBER() OVER([partition by ...] order by ...) if you are really just wanting to return a single row per tar_owner_id.

SELECT
      *
FROM (
      SELECT
            *
          , ROW_NUMBER() OVER (PARTITION BY tbl_assign_role.tar_owner_id 
                               ORDER BY tbl_user.u_updated_date DESC) AS rn
      FROM tbl_user
      JOIN tbl_assign_role
            ON tbl_user.u_id = tbl_assign_role.tar_owner_id
      WHERE is_active = 1
      AND u_id != 1
      AND tar_is_deleted = 0
) AS D
WHERE D.rn = 1
ORDER BY <<some column(s)>>
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY