我有一个包含3个字段的表。此表记录了过去30天内相关国家/地区每天的通话时间。
C_Date Country C_Time
2012-10-01 India 1316
2012-10-01 USA 12
2012-10-01 UK 132
2012-10-01 Kuwait 134
2012-10-02 UK 135
2012-10-02 USA 136
2012-10-02 Singapore 137
我需要使用此记录生成表格和折线图,并尝试编写MySQL查询。基本上我只需要为选定的国家画这个。
说我想要印度,美国和英国;然后我需要拉出这样的记录集:
C_Date | Calling_Time
-----------+----------------------------------
2012-10-01 | 1316,12,132
2012-10-02 | 0,136,135
2012-10-03 | ...
... | ...
这是我的查询:
SELECT C_Date, GROUP_CONCAT(C_Time
ORDER BY Country
SEPARATOR ',') as Calling_Time
FROM Call_Table t
WHERE Country
IN ('India', 'USA', 'UK')
GROUP BY C_Date
ORDER BY C_Date
结果更接近,但它忽略了空洞的结果。
C_Date | Calling_Time
-----------+----------------------------------
2012-10-01 | 1316,12,132
2012-10-02 | 136,135 (expected 0,136,135)
我可以更改我的查询以获取Calling_Time,如 0,136,135 或,136,135 或 null,136,135 ?(具有唯一的段数代表每个国家)
提前致谢!
答案 0 :(得分:2)
尝试此查询 -
SELECT
C_Date,
CONCAT(MAX(IF(country = 'India', C_Time, 0)), ',',
MAX(IF(country = 'USA', C_Time, 0)), ',',
MAX(IF(country = 'UK', C_Time, 0))) Calling_Time
FROM call_table
GROUP BY C_Date
+------------+--------------+
| C_Date | Calling_Time |
+------------+--------------+
| 2012-10-01 | 1316,12,132 |
| 2012-10-02 | 0,136,135 |
+------------+--------------+
答案 1 :(得分:2)
SELECT aa.C_Date,
GROUP_CONCAT(COALESCE(bb.C_Time,0) ORDER BY bb.Country) Calling_Time
FROM
(
SELECT a.Country, b.C_DATE
FROM
(
SELECT DISTINCT Country
FROM TableName t
WHERE Country IN ('India', 'USA', 'UK')
) a CROSS JOIN
(
SELECT DISTINCT DATE(C_Date) C_Date
FROM TableName t
) b
) aa LEFT JOIN TableName bb
ON aa.Country = bb.Country AND
aa.C_DATE = DATE(bb.C_DATE)
GROUP BY aa.C_Date