关于sqlsugar使用sql函数问题

环境:mysql数据库链接 

需求:想统计数据库中的设备号,设备状态,以及设备中子设备的状态 。

分别为俩个表:

1.设备表:设备号(userId),状态 (State)

2.自设备表:设备号(userId),子设备类型(E_type),  子设备状态 (Evalue)

解决方案:

1>使用Sql语句解决

SELECT
  tabledevice.设备编号,
  tabledevice.`终端状态 `,
  GROUP_CONCAT(tabledevice.硬件状态) AS '硬件状态集合' 
FROM (SELECT
    e.UserId AS '设备编号',
    e.State AS '终端状态 ',
    CONCAT(eState.E_type, ":", eState.E_value) AS '硬件状态'
  FROM equipment e
    LEFT JOIN equipmentstate eState
      ON e.UserId = eState.UserId
  ) AS tabledevice
GROUP BY tabledevice.设备编号;

使用Join left  根据 userId链接俩个表,并将字段CONCAT(eState.E_type, ":", eState.E_value)  将硬件类型和状态拼接起来  得到的表数据 重命名为 表tabledevice

然后将表分组 ,分别统计为 UserId State 和状态集合、

注意 GROUP_CONCAT() 是将当前整个分组集合中的某一列,拼成一行数据。如果未分组,则默认整个表某一列全部拼在一起

2>使用SqlSugar解决

还是自己看文档不够认真找了几遍,没找到原生函数。

原本以为:会像数据类型转换一样,使用 SqlFunc 去转换数据。结果没有。哈哈

实际是SqlSugar  可以简介使用sql函数的。

例如:

List<StudentGroup> list9 = db.Queryable<Student>().Where(c => c.id < 20).GroupBy(it => it.sex).Select<StudentGroup>("Sex,count(*) Count").ToList();

恍然大悟, 一下子清楚了。使用sqlsugar解决上面的数据需求

         var res = db.Queryable<Get_Equipment, Get_EquipmentStateDta>((s1, s2) => new object[] {
                     JoinType.Left ,s1.UserId==s2.UserId
                    }
                   ).Select<Get_Equipment>("s1.UserId,State, CONCAT(s2.E_type, ":", s2.E_value) as hardState");

                    var data = db.Queryable(res).Select<Get_Equipment>("UserId,State,GROUP_CONCAT(hardState) as hardList "
                    ).GroupBy(s1 => s1.UserId).ToList();

数据过滤方式和使用sql语句基本一致。

原始视图:

结果如图示:

原文地址:https://www.cnblogs.com/zhao-y/p/12133610.html