我有一个查询,它按周统计所有票证,但是我需要将其转换为动态的两行报告,以将周初日期移动到列中?
这是我的查询:
SELECT td_type, FROM_DAYS(TO_DAYS(ttDate) -MOD(TO_DAYS(ttDate) -2, 7)) AS week_beginning,
DATE_ADD( DATE(ttDate), INTERVAL (8 - DAYOFWEEK(ttDate)) DAY) week_ending,
count(*)
FROM v_all_tickets
WHERE extract(year from ttDate) = '2018' AND ttCategory IN ('TT')
GROUP BY td_type, FROM_DAYS(TO_DAYS(ttDate) -MOD(TO_DAYS(ttDate) -2, 7))
ORDER BY FROM_DAYS(TO_DAYS(ttDate) -MOD(TO_DAYS(ttDate) -2, 7)) DESC, td_type
当我尝试以下语句时:
SET @sql_dynamic = (
SELECT
GROUP_CONCAT( DISTINCT
CONCAT(
'COUNT( IF(MONTH(ttDate) = '
, FROM_DAYS(TO_DAYS(ttDate) -MOD(TO_DAYS(ttDate) -2, 7))
, ', ttNum,0) ) AS mo_'
, MONTH(ttDate)
)
)
FROM v_all_tickets WHERE extract(year from ttDate) = '2018' AND ttCategory IN ('TT') AND td_type IN ('Fiber','Legacy')
);
SET @sql = CONCAT('SELECT td_type, ',
@sql_dynamic, '
FROM v_all_tickets
GROUP BY td_type WITH ROLLUP'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
关于我在上述声明中做错什么的任何想法?
答案 0 :(得分:0)
正确的MySQL语句是:
SET SESSION group_concat_max_len = 1000000;
DROP TABLE IF EXISTS tmp_results;
CREATE TEMPORARY TABLE tmp_results AS
SELECT td_type, FROM_DAYS(TO_DAYS(ttDate) -MOD(TO_DAYS(ttDate) -2, 7)) AS ttDate, ttCategory, ttNum, Count(ttNum) tickets
FROM v_closed_tickets
WHERE extract(year from ttDate) = '2018' AND ttCategory IN ('TT')
GROUP BY td_type, ttDate
ORDER BY td_type, ttDate ASC;
SELECT CONCAT('
SELECT td_type, ',tickets_by_dates,'
FROM tmp_results
GROUP BY td_type WITH ROLLUP
'
)
INTO @query
FROM
(
SELECT GROUP_CONCAT(CONCAT('IFNULL(COUNT(CASE WHEN ttDate=''',actual_date,''' THEN tickets END), ''-'') AS "',col_name,'"')) tickets_by_dates
FROM (
SELECT actual_date, DATE_FORMAT(actual_date,'%m/%d') AS col_name
FROM (SELECT DISTINCT ttDate AS actual_date FROM tmp_results) AS dates
) dates_with_col_names
) result;
PREPARE statement FROM @query;
EXECUTE statement;
DEALLOCATE PREPARE statement;
感谢所有提供帮助的人!