我正在使用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函数中返回的值来确定开始月份的值(月(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()));
我遇到了一些问题:
以下是完整查询:
#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赋值上抛出语法错误。
答案 0 :(得分:0)
将值分配给@yy
内的select
:
SELECT @yy:= start_day_of_month FROM dashboard.client;