0

我的问题很容易解释:

我需要一个为列选择 DISTINCT 的查询,但我也需要选择其他列,通常没有 DISTINCT。任何人都可以向我展示这样的查询作为示例吗?

它应该是一个通用查询!

谢谢。

$sql = 'SELECT DISTINCT user_id FROM ' . DONATION_SECURITY_TABLE . " 
        $sql_where 
        ORDER BY payment_status ASC, user_id ASC";

我还需要让这个查询选择其他东西,不仅仅是 user_id 不同,我还需要选择:donation_id、payment_status、pending_reason、txn_id、mc_gross 和金额。

样品表:

donation_id    user_id    mc_gross    payment_status    txn_id (has UNIQUE index)
1              4          5.00        Completed         g54g4
2              5          10.00       Pending           54yhh
3              4          6.00        Pending           54yhg
4              7          15.00       Completed         fdhgf

查询应返回:user_id 的 DISTINCT,不同的user_id 的 mc_gross 的总和,最新的 payment_status(对于 user_id = 4 将返回 Pending)。

4

2 回答 2

2

这应该有效:

select t1.user_id, 
       t1.donation_id, 
       t1.payment_status, 
       t1.pending_reason,
       t1.txn_id, 
       t2.sum_gross, 
       t1.amount
from the_table t1
join (
   select max(donation_id) as max_id, 
          sum(mc_gross) as sum_gross,
          user_id
   from the_table
   group by user_id
) t2 on t2.max_id = t1.donation_id
    and t2.user_id = t1.user_id;
于 2012-09-27T19:45:08.573 回答
0

试试这个:

select T2.USER_ID, T2.TOTAL_MC_GROSS, T2.LAST_DONATION_ID, 
T1.PAYMENT_STATUS, T1.TXN_ID, T1.PENDING_REASON   from
MY_TABLE T1 inner join
(
select USER_ID, SUM(MC_GROSS) AS TOTAL_MC_GROSS , 
MAX(DONATION_ID) AS LAST_DONATION_ID
from MY_TABLE 
group by USER_ID
) 
T2
on T1.DONATION_ID = T2.DONATION_ID
于 2012-09-27T20:19:01.750 回答