簡體   English   中英

從另一個記錄分組的表中獲取第一條記錄-PHP,MYSQL

[英]Getting the first record from a table grouped by another record - PHP, MYSQL

client_id pet_id   clinic_id invoice_date total service unqid
20.20003  20.26777 20        1/24/2015    100        1     1
20.20001  20.26355 20        1/11/2015     50        2     2
20.20001  20.26355 20        1/12/2015    200              4
20.20001  20.26355 20        1/13/2015    600              5
20.20003  20.26777 20        1/15/2015    350              6

從上表中,我正在嘗試執行一個SQL查詢,該查詢為我提供按“ pet_id”分組的第一個(最低)“ invoice_date”的“總計”。

使用此方法,我可以獲得第一張發票的平均值。 問題是我無法使它正常工作。

我努力了:

mysql_query("SELECT total FROM invoice WHERE clinic_id='$clinic_id' GROUP BY pet_id ORDER BY invoice_date ASC");  

但這給了我50,100應該是50和350(Unqid 2和6)。

我將如何完成? 另外,為什么我的查詢不起作用? 我認為這會給我總計以pet_id分組(確保每只寵物只收到1張發票),並以最低的invoice_date排序(確保第一個發票)。

SELECT total 
FROM 
 (SELECT * from total order by invoice_date ASC) as invoice 
WHERE clinic_id='$clinic_id' 
GROUP BY pet_id 

正如Strawberry所提到的,此語法可以解決。 使用GROUP BY條件時,您的選擇應始終使用聚合方法。

目前,andrei.mihail.nicolae提出的語法有效,但您不知道要花多長時間。

我使用聚合方法為您提出此解決方案:

select a.*
from invoice as a
,(
    select pet_id, min(invoice_date) as invoice_date
    from invoice
    group by pet_id
) as b
where a.pet_id = b.pet_id
and a.invoice_date = b.invoice_date

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM