小编典典

MySQL加条件的多列值

sql

我有以下架构(两个表):

**APPS**

   | ID (bigint)  | USERID (Bigint) | USAGE_START_TIME (datetime)    | 
    ------------------------------------------------------------------
   |  1           |        12       |         2013-05-03 04:42:55    |
   |  2           |        12       |         2013-05-12 06:22:45    |
   |  3           |        12       |         2013-06-12 08:44:24    |
   |  4           |        12       |         2013-06-24 04:20:56    |
   |  5           |        13       |         2013-06-26 08:20:26    |
   |  6           |        13       |         2013-09-12 05:48:27    |


**USAGE**

   | ID (bigint)  | APPID (bigint) |   DEVICEID (bigint)  | HIGH_COUNT (bigint) |  MEDIUM_COUNT (bigint)  |
    --------------------------------------------------------------------------------------------------------
   |  1           |        1       |                  2    |       400           |                   200   |
   |  2           |        1       |                  3    |       200           |                   100   |
   |  3           |        2       |                  3    |       350           |                    40   |
   |  4           |        3       |                  4    |         2           |                   400   |
   |  5           |        4       |                  2    |         4           |                    30   |
   |  6           |        5       |                  3    |        50           |                   300   |

解释:

因此,有两个表。现在,我想找到以下内容:

给定一个USERID,获​​取HIGH_COUNT和MEDIUM_COUNT之和。在计算SUM时,应注意:如果在USAGE中多次使用同一设备,则在计算总和时应考虑具有最新信息(基于APPS.USAGE_START_TIME)的记录。

例如:

对于上述架构,结果应为(对于userid = 12):

   | HIGH_COUNT (bigint)  | MEDIUM_COUNT (Bigint) |
    -----------------------------------------------
   |                356   |                   470 |

SQL小提琴:http://sqlfiddle.com/#!2 /
74ae0f


阅读 186

收藏
2021-05-30

共1个答案

小编典典

如果用户APPS在一台设备上使用多个,则该查询将使用APPS具有最高值的行usage_start_time

select  a.userid
,       sum(u.high_count)
,       sum(u.medium_count)
from    apps a
join    `usage` u
on      u.appid = a.id
join    (
        select  u.device_id
        ,       a.userid
        ,       max(a.usage_start_time) as max_start_time
        from    apps a
        join    `usage` u
        on      u.appid = a.id
        group by
                u.device_id
        ,       a.userid
        ) filter
on      filter.device_id = u.device_id
        and filter.userid = a.userid
        and filter.max_start_time = a.usage_start_time
group by
        a.userid

在您的数据集中,它将5, 3, 4为user选择使用情况行12

看到它在SQL Fiddle上运行。

2021-05-30