简体   繁体   中英

How to count multiple columns grouping by rows in MySQL?

I have two tables, "keywords" and "stats" and want to know per keyword how many results each merchant has. So one row per keyword.

Desired result eg:

KWD    | RESULTS Amazon | RESULTS eBay
test     3                5
second   6                2

The tables:

create table keywords
(
    ID           mediumint unsigned auto_increment
        primary key,
    KEYWORD      varchar(255)                                                     null
);

create table stats
(
    MERCHANT_ID tinyint unsigned                   not null,
    TYPE_ID     mediumint unsigned                 not null comment 'the ID of the coresponding type. E.g. kw_id from keywords',
    RESULTS     smallint unsigned                  null,
    DATE        date                               not null,
    primary key (DATE, MERCHANT_ID, TYPE_ID)
)
    comment 'How many results does each merchant have per search?';

Sample data:

-- keywords
insert into test.keywords (ID, KEYWORD) values (1, 'testing');
insert into test.keywords (ID, KEYWORD) values (2, 'blablub');

-- stats
insert into test.stats (MERCHANT_ID, TYPE_ID, RESULTS, DATE) values (1, 1, 33, '2021-07-06');
insert into test.stats (MERCHANT_ID, TYPE_ID, RESULTS, DATE) values (1, 2, 3, '2021-07-06');
insert into test.stats (MERCHANT_ID, TYPE_ID, RESULTS, DATE) values (2, 1, 22, '2021-07-06');
insert into test.stats (MERCHANT_ID, TYPE_ID, RESULTS, DATE) values (2, 2, 6, '2021-07-06');

The query:

select
       kwd.KEYWORD,
       mss.MERCHANT_ID,
       mss.RESULTS
from keywords kwd
LEFT JOIN stats mss ON mss.TYPE_ID = kwd.ID
where
    date = 20210705
group by kwd.ID

There are about 10 merchants. Is it possible to get one row per keyword and have the number of results per merchant in seperate colunns?

Try something like this:

select
  kwd.KEYWORD,
  SUM(IF(mss.MERCHANT_ID = 'amazon', mss.RESULTS, 0)) as `amazon_sum`,
  SUM(IF(mss.MERCHANT_ID = 'eBay', mss.RESULTS, 0)) as `eBay_sum`
    
from keywords kwd
    LEFT JOIN stats mss ON mss.TYPE_ID = kwd.ID
    where
        date = 20210705
    group by kwd.ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM