Servicestack ormlite window functions

余生颓废 提交于 2021-02-11 15:19:43

问题


I am using version 4.5.14 of Servicestack ormlite

Following are my domain classes

     public class Network 
        {
            [PrimaryKey]
            public string Id { get; set; }
            public string Name { get; set; }
            [CustomSelect("NULL")]
            public bool? InMaintenance { get; set; }
        }

     public class NetworkMain
        {
            [PrimaryKey]
            public string Id { get; set; }    
            [ForeignKey(typeof(Network))]
            public string NetworkId { get; set; }
            public DateTime? EndDate { get; set; }
         }   
    

1 network may have 1 or NetworkMain records. here InMaintenance is not an actual Network table column. I want to compute InMaintenance value based on the related records from NetworkMain table

Following is the query I had written

 var q = connection.From<Domain.Network>()
                    .LeftJoin<NetworkMain>()
                    .Select<Domain.Network, NetworkMain>(
                        (networks, maintenance) => new
                        {
                            networks,
                            InMaintenance = Sql.Custom(
                                "CASE WHEN (dbo.NetworkMain.NetworkId is null  OR " +
                                "( dbo.NetworkMaint.NetworkId is not null AND dbo.NetworkMaintenance.EndDate is not null))  " +
                                "THEN 0 ELSE 1 END")
                        })
                    .OrderBy(x => x.Name);

Which provides duplicate Network records (each for NetworkMain record) with the only difference in InMaintenance column, which is due to left join with NetworkMain.

To get only one record per network irrespective of associated NetworkMain records what changes need to be done in the above query?

NOTE: I have written the following SQL query to get the result I wanted but could not convert to Ormlite syntax

SELECT "Network".*, 
        CASE WHEN (newtable.NetworkId is null  OR ( newtable.NetworkId is not null
         AND newtable.EndDate is not null))  THEN 0 ELSE 1 END AS InMaintenance     
FROM "Network" LEFT JOIN  
(select  ROW_NUMbER() OVER(PARTITION BY NetworkMain.networkid ORDER BY ENDDATE)
 as rownum, enddate,networkid from  "dbo"."NetworkMain" ) as newtable 
ON  ("Network"."Id" = newtable.networkid AND rownum =1)

Please help. Thanks Amol

来源:https://stackoverflow.com/questions/65129435/servicestack-ormlite-window-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!