SQL减少内部查询中的列数

时间:2014-04-18 14:48:16

标签: mysql sql

我有一个问题:

select  
    count(*), paymentOptionId 
from 
    payments 
where 
    id in (select min(reportDate), id 
           from payments 
           where userId in (select distinct userId 
                            from payments 
                            where paymentOptionId in (46,47,48,49,50,51,52,53,54,55,56)) 
           group by userId)
group by 
    paymentOptionId;

问题所在是“select min(reportDate),id”,此查询必须返回1列结果,但我无法实现如何在需要分组时执行此操作。

数据集看起来像

+----+--------+--------+-----------+---------------------+--------+----------+-----------------+
| id | userId | amount | userLevel | reportDate          | buffId | bankQuot | paymentOptionId |
+----+--------+--------+-----------+---------------------+--------+----------+-----------------+
|  9 |  12012 |      5 |         5 | 2014-02-10 23:07:57 |   NULL |     NULL |               2 |
| 10 |  12191 |      5 |         6 | 2014-02-10 23:52:12 |   NULL |     NULL |               2 |
| 11 |  12295 |      5 |         6 | 2014-02-11 00:12:04 |   NULL |     NULL |               2 |
| 12 |  12295 |      5 |         6 | 2014-02-11 00:12:42 |   NULL |     NULL |               2 |
| 13 |  12256 |      5 |         6 | 2014-02-11 00:26:25 |   NULL |     NULL |               2 |
| 14 |  12256 |      5 |         6 | 2014-02-11 00:26:35 |   NULL |     NULL |               2 |
| 16 |  12510 |      5 |         5 | 2014-02-11 00:42:58 |   NULL |     NULL |               2 |
| 17 |  12510 |      5 |         5 | 2014-02-11 00:43:08 |   NULL |     NULL |               2 |
| 18 |  12510 |     18 |         5 | 2014-02-11 00:45:16 |   NULL |     NULL |               3 |
| 19 |  12510 |      5 |         6 | 2014-02-11 01:00:10 |   NULL |     NULL |               2 |
+----+--------+--------+-----------+---------------------+--------+----------+-----------------+

2 个答案:

答案 0 :(得分:0)

您似乎想要为每个用户报告最早ReportDate的各种付款方式及其计数。

如果是这样,这是另一种方法

select p.paymentOptionId, count(*) 
from payments p
where paymentOptionId in (46,47,48,49,50,51,52,53,54,55,56) and
      not exists (select 1
                  from payments p2
                  where p2.userId = p.userId and
                        p2.ReportDate < p.ReportDate
                 )
group by paymentOptionId;

这与您的查询完全相同,因为这只会报告付款类型列表,而您可能希望为曾经拥有其中一种类型的任何人提供第一种付款方式。不过,我不确定你想要的是什么。

答案 1 :(得分:0)

select count(*), paymentOptionId
    from 
        (select userId, min(reportdate), paymentOptionId 
            from payments as t1 
            group by userId, paymentOptionId) as t2 
    group by paymentOptionId

Fiddle

首先获取每个用户的最小报告日期(所以第一个条目),对于每种类型(因此对于有2种类型的用户有两条记录),然后计算它们按类型分组(aka paymentOptionId)。 / p>

顺便说一句,您当然可以在select子句中删除from中选择的属性,它们只是存在,因此您可以复制粘贴它并查看它一步一步给出的结果