为mysql中的同一选择中的另一列选择列的datediff值使用

时间:2016-11-03 06:24:40

标签: mysql

在select语句中,count_date使用datediff函数,我正在尝试乘以count_date*(t3.Rate/30) as payble,如下所示:

@var:= datediff(
  (case when datediff(@todate, Max(t1.attnDate))!=1 then Max(t1.attnDate) else @todate end),
  (case when datediff(Min(t1.attnDate), @fromdate)>1 then Min(t1.attnDate) else @fromdate end)
)+1 as count_date, @var*(t3.Rate/30) as payble

输出:

TraineeID   count_date  payble
31028          5    666.6667
31040          5    666.6667
31135          12   666.6667
31214          12   666.6667
31220          5    666.6667
31312          12   666.6667
31319          12   666.6667
31347          12   666.6667
31388          12   666.6667
31423          12   666.6667
31426          5    666.6667
31445          5    666.6667
31446          5    666.6667

主要查询:

SET @batch='Welding/SSTS-M/09/01';
SET @fromdate='2016-09-19';
SET @todate='2016-09-30';

SELECT t1.TraineeID,
    datediff(
        (case when datediff(@todate, Max(t1.attnDate))!=1 then Max(t1.attnDate) else @todate end),
        (case when datediff(Min(t1.attnDate), @fromdate)>1 then Min(t1.attnDate) else @fromdate end)
    )+1 as count_date 

FROM tbl_attendance_processed t1
JOIN tbl_assigned t2 on t1.TraineeID=t2.TraineeID
LEFT JOIN tbl_foodlodging_rate t3 on t2.Round=t3.Round
LEFT JOIN tbl_trainee_status t4 on t1.TraineeID=t4.TraineeID
LEFT JOIN tbl_trade t5 ON t2.Trade=t5.ID
WHERE t2.BatchID=@batch and t1.attnDate>=@fromdate AND t1.attnDate<=@todate and t2.Reported=1 and t2.Status=1
GROUP by t1.TraineeID;

1 个答案:

答案 0 :(得分:1)

我稍微修改了你的查询。试试以下。

SELECT tablea.*, tablea.count_date*(tablea.Rate/30) AS payble
FROM
(   SELECT t1.TraineeID,
        datediff(
            (case when datediff(@todate, Max(t1.attnDate))!=1 then Max(t1.attnDate) else @todate end),
            (case when datediff(Min(t1.attnDate), @fromdate)>1 then Min(t1.attnDate) else @fromdate end)
        )+1 as count_date, t3.Rate

    FROM tbl_attendance_processed t1
    JOIN tbl_assigned t2 on t1.TraineeID=t2.TraineeID
    LEFT JOIN tbl_foodlodging_rate t3 on t2.Round=t3.Round
    LEFT JOIN tbl_trainee_status t4 on t1.TraineeID=t4.TraineeID
    LEFT JOIN tbl_trade t5 ON t2.Trade=t5.ID
    WHERE t2.BatchID=@batch and t1.attnDate>=@fromdate AND t1.attnDate<=@todate and t2.Reported=1 and t2.Status=1
    GROUP by t1.TraineeID
) AS tablea;