我目前正在使用支持MySql 5.0的phpMyAdmin。
我有以下两个表:
Master Facebook Insights
------------------------
Client ID Client Name Date Top Likes By Gender
--------- ----------- ------ --------------------
1 Client1 2012-01-01
1 Client1 2012-02-01
2 Client2 2012-01-01
2 Client2 2012-02-01
...etc. (the dates are always the beginning of each month for however many months
& clients exist)
Likes By Demographic
----------------
Date Demographic1 Demographic2 Demographic3 Client
------ ------------ ------------ ------------ ------
0000-00-00 M.35-44 M.45-54 M.25-34 1
2012-01-01 53 44 28 1
2012-01-02 53 46 29 1
...etc.
0000-00-00 M.18-24 M.35-44 M.25-34 1
2012-02-01 374 221 194 1
2012-02-02 374 222 195 1
...etc.
0000-00-00 F.35-44 F.25-34 M.35-44 2
2012-01-01 194 182 83 2
2012-01-02 194 182 83 2
...etc.
0000-00-00 F.35-44 F.25-34 M.35-44 2
2012-02-01 196 180 83 2
2012-02-02 197 180 83 2
...etc.
对于Likes By Demographic表: 每个客户列出每个月的所有日期;当一个新月开始时, 有一组新的人口统计数据可能会或可能不会完全相同 和上个月一样。这是因为数据是从CSV导入的,将人口统计信息按照最高“喜欢”的顺序排列,因此这通常会逐月变化。这也是个人人口统计信息不是列标题的原因(因为它们不一致)。
我的问题如下: 我希望在第一个表格的“按性别排名前列”列中列出每个客户每月的前3位受众特征,如下所示:
Client ID Client Name Date Top Likes By Gender
--------- ----------- ------ --------------------
1 Client1 2012-01-01 M.35-44, M.45-54, M.25-34
1 Client1 2012-02-01 M.18-24, M.35-44, M.25-34
2 Client2 2012-01-01 F.35-44, F.25-34, M.35-44
2 Client2 2012-02-01 F.35-44, F.25-34, M.35-44
使用子查询让我很困惑。以下是我一直试图修复的(错误)代码。问题是,它只是为第一个客户提取前三个人口统计数据(M.35-44,M.45-54,M.25-34),并在所有客户和日期的整个列中重复它们。 我是在正确的轨道上,还是有更简单/更正确的方法来做到这一点?
UPDATE `Master Facebook Insights`
SET `Top Likes By Gender` =
(select * from
(SELECT DISTINCT CONCAT(`Demographic1`,', ',`Demographic2`,', ',`Demographic3`)
FROM `Likes By Demographic` t1
JOIN `Master Facebook Insights` t2
ON t1.`Client` = t2.`Client ID`
WHERE t1.`Date` = '0000-00-00'
AND t2.`Date` =
(
SELECT MIN(`Date`)
FROM `Likes By Demographic`
WHERE `Date` > '0000-00-00'
AND `Client` = t2.`Client ID`
GROUP BY `Date`
ORDER BY `Date` ASC
LIMIT 1
)
)inner1 limit 1)
非常感谢您的帮助!
答案 0 :(得分:0)
只需使用原始的Likes_By_Demographic表,即可:
select
client_id,
date,
concat(demo1,', ',demo2,', ',demo3) `top_likes`
from likes_by_demographic
group by client_id, date
order by client_id, date;
...将产生(伪数据):
| CLIENT_ID | DATE | TOP_LIKES |
-----------------------------------------------------------------------
| 1 | January, 01 2012 00:00:00-0800 | M.35-44, M.25-34, 195 |
| 1 | February, 01 2012 00:00:00-0800 | M.25-34, M.35-44, 195 |
| 1 | March, 01 2012 00:00:00-0800 | M.25-34, 195, 169 |
| 2 | January, 01 2012 00:00:00-0800 | F.45-54, 210, 195 |
| 2 | February, 01 2012 00:00:00-0800 | F.45-54, 210, 75 |