如何在sql中显示具有相同id的最小数值

时间:2014-02-18 07:46:30

标签: mysql sql

我有这样的查询

SELECT 
  parentOrder.uid,
  patient_name,
  created_date,
  created_time,
  order_test_discount_tbl.standard_rate AS test_rate,
  (SELECT 
    parentOrder.grand_total - SUM(amount_paid) 
  FROM
    order_payment_tbl 
  WHERE order_payment_tbl.date <= parentPayment.date 
    AND order_payment_tbl.order_id = parentOrder.id) AS order_due,
  test_pkg_tbl.name AS `name` 
FROM
  order_tbl AS parentOrder 
  RIGHT JOIN order_payment_tbl AS parentPayment 
    ON parentOrder.id = parentPayment.order_id 
  LEFT JOIN order_test_discount_tbl 
    ON parentOrder.id = order_test_discount_tbl.order_id 
  LEFT JOIN test_pkg_tbl 
    ON order_test_discount_tbl.test_pkg_uid = test_pkg_tbl.uid 
  LEFT JOIN referral_tbl 
    ON parentOrder.referral_id = referral_tbl.id 
  LEFT JOIN blanket_order_tbl 
    ON parentOrder.blanket_order_id = blanket_order_tbl.id 
WHERE parentPayment.date >= '2014-02-07' 
  AND parentPayment.date <= '2014-02-08' 
  AND test_pkg_tbl.name = 'kkk' 
  AND parentOrder.status != 'Cancelled' 
  AND order_test_discount_tbl.test_pkg_uid IS NOT NULL 
  AND parentOrder.origin = 'Premises' 
GROUP BY parentOrder.id,
  DATE,
  test_pkg_tbl.name,
  order_test_discount_tbl.standard_rate 
ORDER BY parentOrder.id 

这是表格数据:

uid  patient_name  created_date  created_time  test_rate  order_due  name
JV1  abc           7/2/2014      8:26 AM            1100          0  kkk
JV2  def           7/2/2014      8:26 AM            1100       1000  kkk
JV2  def           7/2/2014      8:26 AM            1100          0  kkk
JV3  ghi           8/2/2014      8:26 AM            1100          0  kkk
JV4  jkl           8/2/2014      8:26 AM            1100          0  kkk

上面的查询返回这样的表。第二行和第三行有相同的uid但order_due是不同的。我只需要显示第二行和第三行中最小order_due的行。我能做什么? Anser应该是这样的

uid  patient_name  created_date  created_time  test_rate  order_due  name
JV1  abc           7/2/2014      8:26 AM            1100          0  kkk
JV2  def           7/2/2014      8:26 AM            1100          0  kkk
JV3  ghi           8/2/2014      8:26 AM            1100          0  kkk
JV4  jkl           8/2/2014      8:26 AM            1100          0  kkk

1 个答案:

答案 0 :(得分:0)

在以下外部查询中包装您编写的查询:

SELECT uid, patient_name, created_date, created_time, test_rate, MIN(order_due), name
FROM
( ***your query *** ) q
GROUP BY  uid, patient_name, created_date, created_time, test_rate, name