我们如何在 ORMLite ServiceStack 中使用 MySql Select Case 构造

问题描述 投票:0回答:1
Select
    sum(
        CASE
            WHEN e01f04 < '2024-02-01' THEN DATEDIFF(ADDDATE(e01f04, INTERVAL (e01f05 - 1) DAY), '2024-02-01') + 1
            WHEN ADDDATE(e01f04, INTERVAL (e01f05 - 1) DAY) > '2024-02-29' THEN DATEDIFF(e01f04, '2024-02-29') + 1
            ELSE DATEDIFF(ADDDATE(e01f04, INTERVAL (e01f05 - 1) DAY), e01f04) + 1
        END
    ) AS Leave_Count
    , E01F06
FROM
    lve01
where
        e01f02 = 1
    AND
        e01f07 = 2
    AND
        (e01f04 >= '2024-02-01' AND
        e01f04 <= '2024-02-29')
    OR
        (ADDDATE(e01f04, INTERVAL (e01f05 - 1) DAY) >= '2024-02-01' AND
        ADDDATE(e01f04, INTERVAL (e01f05 - 1) DAY) <= '2024-02-29');

e01f02 - 员工 ID

e01f04 - 休假开始日期

ADDDATE(e01f04, INTERVAL (e01f05 - 1) DAY) - 保留最后日期

e01f05 - 没有。叶子

e01f07 - 休假状态(其中 2 = 已批准)

代码解释 - 上面的查询是为了获取 2024 年 2 月员工 ID = 1 的批准休假总数

如何使用 ORMLite 功能或查询执行上述查询?

更新

SqlExpression<LVE01> sqlExp = db.From<LVE01>()
    .Where(l => l.e01f02 == EmployeeId && l.e01f07 == LeaveStatus.Approved)
    .Where($"(e01f04 >= '{MonthFirstDate}' AND e01f04 <= '{MonthLastDate}')")
    .Or($"(ADDDATE(e01f04, INTERVAL (e01f05 - 1) DAY) >= '{MonthFirstDate}' AND ADDDATE(e01f04, INTERVAL (e01f05 - 1) DAY) <= '{MonthLastDate}')");

sqlExp.SelectExpression = $"SELECT sum( CASE WHEN e01f04 < '{MonthFirstDate}' THEN DATEDIFF(ADDDATE(e01f04, INTERVAL (e01f05 - 1) DAY), '{MonthFirstDate}') + 1 WHEN ADDDATE(e01f04, INTERVAL (e01f05 - 1) DAY) > '{MonthLastDate}' THEN DATEDIFF(e01f04, '{MonthLastDate}') + 1 ELSE DATEDIFF(ADDDATE(e01f04, INTERVAL (e01f05 - 1) DAY), e01f04) + 1 END) AS Leave_Count";

我尝试并能够使用 ORMLite 创建查询,但当然我需要在某些地方使用 mysql 查询文字(例如 select 表达式)。

我可以让查询更加基于函数吗?

c# mysql asp.net servicestack ormlite
1个回答
0
投票

您需要使用自定义 SQL,但您应该能够使用类型化表达式来比较 DateTime,我建议使用数据库参数而不是字符串插值,并且您可以使用

UnsafeSelect
代替填充
SelectExpression
,例如:

var q = db..From<LVE01>()
    .Where(l => l.e01f02 == EmployeeId && l.e01f07 == LeaveStatus.Approved)
    .And(x => x.e01f04 >= MonthFirstDate && x.e01f04 <= MonthLastDate)
    .Or("(ADDDATE(e01f04, INTERVAL (e01f05 - 1) DAY) >= {0} AND ADDDATE(e01f04, INTERVAL (e01f05 - 1) DAY) <= {1})", 
        MonthFirstDate, MonthLastDate)
     .UnsafeSelect("sum(CASE WHEN e01f04...");
© www.soinside.com 2019 - 2024. All rights reserved.