我可以从table
获取此类数据吗?| id_outlet| date | count(msisdn) |
| 34.10.1 | 2014-08 | 0 |
| 34.10.1 | 2014-09 | 3 |
| 34.10.1 | 2014-10 | 2 |
| 34.10.2 | 2014-08 | 1 |
| 34.10.2 | 2014-09 | 0 |
| 34.10.2 | 2014-10 | 0 |
所以我有2张桌子
1.桌面插座(独特)
2.桌子销售(桌面细节)
正如你在我的第二张表中看到的那样,有3个周期(2014-08,2014-09,2014-10)
我希望在第一个表中加入带有id_outlet的periode,就像那个例子一样
我可以吗?
请帮帮我
答案 0 :(得分:0)
别担心,快乐!
SELECT
o.id_outlet,
SUBSTRING(s.date,1,7) AS periode,
o.branch
FROM outlet o LEFT JOIN sales s ON o.id_outlet = s.id_outlet
WHERE (o.STATUS LIKE 'STREET%')
ORDER BY o.id_outlet, YEAR(s.DATE), MONTH(s.DATE), branch
答案 1 :(得分:0)
您需要此查询:
SELECT
o.id_outlet,
d.period AS periode,
o.branch,
count(msisdn)
FROM dates d LEFT JOIN outlet o ON d.period = SUBSTRING(o.date,1,7) LEFT JOIN sales s ON o.id_outlet = s.id_outlet
WHERE (o.STATUS LIKE 'STREET%')
GROUP BY CONCAT(d.period, '@', s.id_outlet)
ORDER BY o.id_outlet, d.period, branch
答案 2 :(得分:0)
使用CROSS JOIN: -
SELECT
o.id_outlet,
s_main.periode,
o.branch,
count(msisdn)
FROM
(
SELECT DISTINCT SUBSTRING(date,1,7) AS periode
FROM sales
) s_main
CROSS JOIN outlet o
LEFT OUTER JOIN sales s
ON s_main.periode = SUBSTRING(s.date,1,7)
AND o.id_outlet = s.id_outlet
WHERE (o.STATUS LIKE 'STREET%')
GROUP BY s_main.periode, o.branch, o.id_outlet
如果您有一个日期表,那么您可以使用它而不是子查询来获取日期(这也避免了在一个月没有销售额的情况下在结果中没有日期的潜在问题任何出口)。