I have a table called visits
where concat(s_id, c_id)
is unique and id
is the primary key. s_id
is the ID number of a website and c_id
is a campaign ID number. I want to show all the hits each campaign is getting and group by the site. I want each site on a single row
我有一个名为visits的表,其中concat(s_id,c_id)是唯一的,id是主键。 s_id是网站的ID号,c_id是广告系列ID号。我想显示每个广告系列获得的所有匹配并按网站分组。我希望每个站点都在一行上
+-----+------+------+------+
| id | s_id | c_id | hits |
+-----+------+------+------+
| 1 | 13 | 8 | 245 |
| 2 | 13 | 8 | 458 |
| 3 | 13 | 3 | 27 |
| 4 | 13 | 4 | 193 |
| 5 | 14 | 1 | 320 |
| 6 | 14 | 1 | 183 |
| 7 | 14 | 3 | 783 |
| 8 | 14 | 4 | 226 |
| 9 | 5 | 8 | 671 |
| 10 | 5 | 8 | 914 |
| 11 | 5 | 3 | 548 |
| 12 | 5 | 4 | 832 |
| 13 | 22 | 8 | 84 |
| 14 | 22 | 1 | 7 |
| 15 | 22 | 3 | 796 |
| 16 | 22 | 4 | 0 |
+----+------+------+-------+
I would like to have the following result set:
我想要以下结果集:
s_id | hits | hits | hits| hits
13 | 245 | 458 | 27 | 193
14 | 320 | 183 | 783 | 226
5 | 671 | 914 | 548 | 832
22 | 84 | 7 | 796 | 0
Here is what I have tried which does not pull all the hits columns back.
这是我试过的,不会把所有的命中列拉回来。
SELECT v.*, v2.* FROM visits v
INNER JOIN visits v2 on v.s_id = v2.s_id
GROUP BY s_id
How can I get multiple rows into columns?
如何将多行放入列中?
1 个解决方案
#1
2
If your'e data set is not crazy huge and you are just trying to get the multiple rows as a single row.... one way to do this...
如果你的数据集不是很疯狂,而你只是想把多行作为一行......一种方法可以做到这一点......
SELECT
s_id,
GROUP_CONCAT(hits SEPARATOR ',') as hits_list
FROM
visits
GROUP BY s_id
Since it doesn't use any joins or subqueries etc, i find this way to be quite fast.
由于它不使用任何连接或子查询等,我发现这种方式非常快。
you can later split/explode the data based on the ',' separator in PHP or whatever language you are using.
您可以稍后根据PHP中的','分隔符或您正在使用的任何语言拆分/分解数据。
$hits = explode($hits_list, ','); //get them in an array
#1
2
If your'e data set is not crazy huge and you are just trying to get the multiple rows as a single row.... one way to do this...
如果你的数据集不是很疯狂,而你只是想把多行作为一行......一种方法可以做到这一点......
SELECT
s_id,
GROUP_CONCAT(hits SEPARATOR ',') as hits_list
FROM
visits
GROUP BY s_id
Since it doesn't use any joins or subqueries etc, i find this way to be quite fast.
由于它不使用任何连接或子查询等,我发现这种方式非常快。
you can later split/explode the data based on the ',' separator in PHP or whatever language you are using.
您可以稍后根据PHP中的','分隔符或您正在使用的任何语言拆分/分解数据。
$hits = explode($hits_list, ','); //get them in an array