SELECT 一列上的 DISTINCT(SQL Server 2005 或更高版本)使用 php

SELECT DISTINCT on one column (SQL Server 2005 or greater) using php

我已经尝试了 Whosebug 中提供的代码,但仍然出现错误。有人能告诉我我哪里弄错了吗?谢谢你!这是我的代码:

$allOrdersFromToday = $Microinvest->MSelectList('SELECT * ROW_NUMBER() OVER (PARTITION BY Acct ORDER BY ID) AS RowNumber FROM Operations WHERE Date = "' . $todayDate . '" AND OperType = 2 ORDER BY Acct DESC) AS a', '*', 'a.RowNumber = 1');

应该输出为:

SELECT  *
FROM    (SELECT *,
                ROW_NUMBER() OVER (PARTITION BY Acct ORDER BY ID) AS RowNumber
         FROM   Operations
         WHERE  Date = "' . $todayDate . '" AND OperType = 2 ORDER BY Acct DESC) AS a
WHERE   a.RowNumber = 1

但是我收到一个错误...:(

Warning: mssql_query(): message: Incorrect syntax near the keyword 'SELECT'. (severity 15) in /var/www/functions/MssqlLibry.php on line 29

在大多数情况下,

SQL 服务器不支持在子查询中使用 order by。试试这个:

SELECT  a.*
FROM (SELECT o.*,
             ROW_NUMBER() OVER (PARTITION BY Acct ORDER BY ID) AS RowNumber
      FROM Operations o
      WHERE  Date = "' . $todayDate . '" AND
             OperType = 2
     ) a
WHERE a.RowNumber = 1
ORDER BY a.Acct DESC;

此外,您可能会遇到日期格式方面的问题。您应该使用参数化查询,而不是将值替换为字符串。