简体   繁体   中英

MYSQL Retrive last record in each group and sort by location

Here's my table

ID   Name   Qty   Location
1    B      1     Office
2    A      20    Office
3    A      50    Home
4    A      5     Office

this is the sql statement i'm currently using:

select t1.* from itemtable t1 
    left join itemtable t2 on (t1.name = t2.name and t1.id < t2.id) 
    where t2.id is null AND t1.location = 'office' 
    order by name ASC

Which works fine in phpadmin, but when I run it on my page, it sorts 'id' first. meaning i'd get B (because id = 1) then A

if it helps, here's my code

<table class="table table-hover">
    <thead>
        <tr>
        <th style="text-align:left">ID.</th>
            <th style="text-align:left">Item</th>
        <th style="text-align:center">Quantity</th>
        </tr>
    </thead>
    <tbody>
        <?php 
        $b = 0;
        $x = 1;
        while($row = $result->fetch_assoc()) {
            echo "<tr><td style=\"text-align:left\">". $x. "</td><td style=\"text-align:left\">". $row[name]. "</td><td style=\"text-align:center\">". $row[qty]. "</td></tr>";
        $b = $b + 1;
        $x = $x + 1;
        }?>
    </tbody>
</table>

the final output will be

ID   Name   Qty
1    B      1
2    A      75

how do I make it sort by name? Thanks

尝试以下一项

Select t1.* FROM  (SELECT * FROM itemtable ORDER BY ID DESC ) as t1 group by Location

检查一下:

select min(ID) as ID,Name,sum(qty) as Qty from itemtable group by location order by Name DESC

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