1

我想从日期中创建动态别名,如下所示。每天都会有不同的列名。我用变量尝试过,但它不起作用。解决方案应该如下所示,或者如果我不需要使用变量,它也可以。

SET @today = CURRENT_DATE(),
    @lastWeek = DATE_ADD(CURRENT_DATE(),INTERVAL -7 DAY);

SELECT date1 AS @today, date2 AS @lastweek FROM table1;

谢谢您的帮助

4

2 回答 2

1

看看这个。我认为这就是你所需要的。

所以你可以这样做:

SET @today = CURRENT_DATE(),
    @lastWeek = DATE_ADD(CURRENT_DATE(),INTERVAL -7 DAY),
    @sql = concat('SELECT date1 AS "', @today, '", date2 AS "', @lastweek, '" FROM table1');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
于 2013-09-13T09:46:32.887 回答
0

这就像给我动态日期列的魅力。

SET @today = CURRENT_DATE(),
    @day1 = DATE_ADD(CURRENT_DATE(),INTERVAL -1 DAY),
    @day2 = DATE_ADD(CURRENT_DATE(),INTERVAL -2 DAY),
    @day3 = DATE_ADD(CURRENT_DATE(),INTERVAL -3 DAY),
    @day4 = DATE_ADD(CURRENT_DATE(),INTERVAL -4 DAY),
    @day5 = DATE_ADD(CURRENT_DATE(),INTERVAL -5 DAY),
    @sql = concat("SELECT JRR_RESULT, COUNT(LEFT(JRR_RESULT,40)) AS 'Total Error Last 
5 Days'"
    ", sum(IF( DATE_FORMAT(CREATION_DATE,'%Y-%m-%d') = '" , @day1, "',1,0) ) AS '", 
@day1, "' "
    ", sum(IF( DATE_FORMAT(CREATION_DATE,'%Y-%m-%d') = '" , @day2, "',1,0) ) AS '", 
@day2, "' "
    ", sum(IF( DATE_FORMAT(CREATION_DATE,'%Y-%m-%d') = '" , @day3, "',1,0) ) AS '", 
@day3, "' "
    ", sum(IF( DATE_FORMAT(CREATION_DATE,'%Y-%m-%d') = '" , @day4, "',1,0) ) AS '", 
@day4, "' "
    ", sum(IF( DATE_FORMAT(CREATION_DATE,'%Y-%m-%d') = '" , @day5, "',1,0) ) AS '", 
@day5, "' "
    " FROM your_table where DATE_FORMAT(CREATION_DATE,'%Y-%m-%d') >= '" , @day5, "' "
    " Group by LEFT(JRR_RESULT,40)"); 

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
于 2019-10-23T19:38:39.303 回答