0

我正在使用 MySQL 制作一份报告,显示特定日期范围和项目的计费小时数。复杂性在于每个项目的日期范围是可变的(不同的开始月份和开始日期)。此信息来自另一个数据库/表中的值。

我在 MySQL 中有以下 UDF:

DELIMITER //

CREATE FUNCTION TimeLeft(startday INT, today INT) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE s INT;
   IF startday < today THEN SET s = 0;
     ELSE SET s = 1;
     END IF;
   RETURN s;
END //

DELIMITER; 

我在以下查询中使用该函数,它应该采用 TimeLeft 函数中返回的值来确定每个项目的开始月份 (month(curdate())-@xx) 和开始日期 (@yy) 的值计算小时数:

AND time_records.record_date >= concat('2012/', month(curdate())-@xx , '/' , @yy)  

以下是我为@xx 和@yy 设置值的方式:

SET @xx = 0; #this is the value that we will use to manipulate the month for the date range
SET @yy = 0;
@yy:= SELECT start_day_of_month FROM dashboard.client; #this doesn't seem to work
SELECT @xx:= TimeLeft(@yy,dayofmonth(curdate()));

我遇到了一些问题:

  1. @yy 没有得到值 - 可能我的语法错误?
  2. 变量设置在代码的顶部,因此它们不会因每个项目而发生应有的变化(每个项目应该有不同的@xx 和@yy,因为每个项目都有不同的开始和结束日期)。

这是完整的查询:

#below is where I assign the variables

SET @xx = 0; #this is the value that we will use to manipulate the month for the date range
SET @yy = 0;
@yy:= SELECT start_day_of_month FROM dashboard.client; #this doesn't seem to work
SELECT @xx:= TimeLeft(@yy,dayofmonth(curdate()));


# below is the MySQL query that is meant to use the variables assigned above

SELECT X.expr1 AS 'Project Name', @monthly_hours - SUM(X.expr2) AS 'Hours Billed
FROM 
  (SELECT 
    projects.name AS expr1
    , sum(time_records.value) AS expr2
  FROM project_objects
  INNER JOIN projects
    ON projects.id = project_objects.project_id
  INNER JOIN time_records
    ON time_records.parent_id = project_objects.id
  WHERE time_records.parent_type = 'Task' 
  AND time_records.record_date >= concat('2012/', month(curdate())-@xx , '/' , @yy)  
  AND time_records.record_date <= curdate()
  GROUP BY projects.name

  UNION

  SELECT 
    projects.name AS expr1
    , sum(time_records.value) as expr2
  FROM projects
  INNER JOIN time_records
    ON projects.id = time_records.parent_id
  WHERE time_records.parent_type = 'Project'
  AND time_records.record_date >= concat('2012/', month(curdate())-@xx , '/' , @yy)     
  AND time_records.record_date <= curdate() 
  GROUP BY projects.name) X
GROUP BY X.expr1

我认为我在哪里分配变量@xx 和@yy 存在一些问题。这些应该为每个单独的项目完成,因此将它们放在顶部可能不是最好的主意。我也不确定我是否正确分配了@yy 值。它应该查询另一个数据库中的表的字段的值,但它不断在@yy 分配给该字段时抛出语法错误。

4

1 回答 1

0

@yy为inside赋值select

SELECT @yy:= start_day_of_month FROM dashboard.client;
于 2012-10-03T19:38:12.067 回答