简体   繁体   中英

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

I have tried the code provided here in stackoverflow, but i still get an error. can someone tell me where im mistaking? thank you! This is my code:

$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');

which should output as:

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

but im getting an error... :(

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

SQL Server does not support order by in subqueries, under most circumstances. Try this:

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;

In addition, you could have a problem because of the format of the date. You should use parameterized queries rather than substituting values into strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM