【问题标题】:Select DISTINCT of a column, but have other columns returned normally选择一列的 DISTINCT,但其他列正常返回
【发布时间】:2012-09-27 19:16:09
【问题描述】:

我的问题很容易解释:

我需要一个为一列选择 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 和 amount。

示例表:

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,distinct-ed user_id 的 mc_gross 的总和,最新的 payment_status(对于 user_id = 4 将返回 Pending)。

【问题讨论】:

  • 请提供示例数据和所需的输出。
  • 您能否向我们展示您拥有的数据以及您想要的查询输出的示例?
  • 为什么不解释你的需求,而不是你需要查询做什么。我不认为 DISTINCT 是你的答案。听起来你想要更多的聚合组。
  • 什么是“通用查询”?你用的是什么数据库?
  • 你的问题没有意义。如果一个 user_id 有多个捐赠,会发生什么?如果输出中每个 user_id 只有一行,那么哪个捐赠行应该贡献donation_id、payment_status 等的值?

标签: php sql distinct


【解决方案1】:

这应该可行:

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;

【讨论】:

  • 你能解释一下我们从哪里得到 mc_gross 的 SUM 吗?
  • @Dugi: nowhere :) 我没有看到这个要求。我编辑了我的答案
【解决方案2】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 2010-12-19
    • 2013-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    相关资源
    最近更新 更多