how to fetch data of table after doing full outer join? - sql

i am having a business problem
having a table which have following
|sku_id |solr_status |entry_context | mrp
1 active 10 20
1 inactive 10 30
1 active 10 22.5
2 inactive 10 10
2 inactive 10 31
filter the data into
table1->active
table2->inactive
now i have to do the according to condition
full outer join on 1 and 2 on sku_id.. Three possible cases
case (1 is not null, 2 is not null) => use 1
case (1 is null, 2 is not null) => use 2
case (1 is not null, 2 is null) => use 1
my code is something like that
val activeCatalog=dataframe.filter('solr_status===true).cache()
val inActiveCatalog=dataframe.filter('solr_status===false).cache()
val fullCatalog=activeCatalog.join(inActiveCatalog,Seq("sku"),joinType = "outer")
fullCatalog.show(false)
val resultCatalog = (activeCatalog,inActiveCatalog) match {
case (activeCatalog,inActiveCatalog) if(activeCatalog.count()!=0L && inActiveCatalog.count()!=0L)=>
fullCatalog.filter('solr_status===true).cache()
case (activeCatalog, inActiveCatalog) if (activeCatalog.count() == 0L && inActiveCatalog.count() != 0L) =>
fullCatalog.filter('solr_status === false).cache()
case (activeCatalog, inActiveCatalog) if (activeCatalog.count() != 0L && inActiveCatalog.count() == 0L) =>
fullCatalog.filter('solr_status === true).cache()
}
so using the approach i am getting ambiguous column error. also my
result data set should maintain the schema for active or inactive
table, doing outer join will create duplicate columns
any help ?

Related

Filter Data based on priority in LINQ

The fields in my Rate Table are Route, VehicleMasterId, VehicleType, Material, Client, UnitRate etc.
The priority order on which I have to fetch a single row is : VehicleNo > Route > Client > VehicleType, Material
Suppose I have 2 rows with same data except 1 has Client and Vehicle Type and the other one has VehicleNo.Then based on my priority, I should pick the rate of the row with VehicleNo.
To excute this In linq I have first picked all the rows with matching data. Here is my code.
public RateMasterDataModel GetRateMasterforCn(Consignment cn){
// I will always pass all the above fields in cn
var rateMaster = (from rate in Context.RateMaster
where rate.FromDate <= cn.Cndate
&& rate.ToDate >= cn.Cndate
&& (rate.VehicleTypeId != null ? rate.VehicleTypeId == cn.VehicleTypeId : true)
&& (rate.VehicleMasterId != null ? rate.VehicleMasterId == cn.VehicleMasterId : true)
&& (rate.ClientId != null ? rate.ClientId == cn.ClientId : true)
&& (rate.RouteId != null ? rate.RouteId == cn.RouteId : true)
&& (rate.MaterialMasterId != null ? rate.MaterialMasterId == cn.MaterialMasterId : true)
select new RateMasterDataModel
{
RateMasterId = rate.RateMasterId,
FromDate = rate.FromDate,
ToDate = rate.ToDate,
ClientId = rate.ClientId ,
VehicleMasterId = rate.VehicleMasterId,
VehicleTypeId = rate.VehicleTypeId,
MaterialMasterId = rate.MaterialMasterId,
UnitRate = rate.UnitRate,
LoadTypeId = rate.LoadTypeId,
LoadingPointId = rate.RouteId,
CalculationMasterId = rate.CalculationMasterId
}).ToList();
}
Please suggest how to filter after this.
You can use below code to get records ordered by VehicleNo > Route
.OrderBy(v=>v.VehicleNo).ThenBy(r=>r.RouteId)
Add multiple .ThenBy() clause as per your column requirement for sorting the data.
You mean to say if the row which doesn't have the vehicalno. filld-up then the row having Route must be selected.is it correct?

Convert SQL Server query to Entity Framework query

I have a SQL Server query like this:
select
month(fact_date) as month,
sum(case when beef_dairy_stat = 1 and param_id = 1 then 1 else 0 end) as cnt
from
user_behave_fact
where
YEAR(fact_date) = 2018
group by
month(fact_date)
order by
month
with a result of
month cnt
------------
1 10
2 20
Now I need to convert this query to its corresponding Entity Framework query.
This is my current attempt:
var sql_rez_ICC = new List<Tuple<int, int>>();
sql_rez_ICC = db.user_behave_fact
.Where(x => x.fact_date.Value.Year == selected_year)
.GroupBy(y => y.fact_date.Value.Month)
.Select(y =>new { month = y.Select(x=>x.fact_date.Value.Month), icc_count = y.Count(x => x.beef_dairy_stat == true && x.param_id == 1) })
.AsEnumerable()
.Select(y => new Tuple<int, int>(y.month, y.icc_count))
.ToList();
However on second .Select, I get an error on month which is
Cannot convert from System.Collection.Generic.IEnumrable to int
y.Select(x=>x.fact_date.Value.Month) returns an IEnumerable<int>. Use y.Key instead.

filter data with entity framework

I'm trying to get the right data
Rooms table
Id | Name
1 Room1
2 Room2
Resources table
Id | Name
1 Resource1
2 Resource2
3 Resource3
RoomResources table
Id | RoomId | ResourceId
1 1 1
2 1 2
3 1 3
4 2 2
5 2 3
I want select a room with Resource1 and Resource2
I'm using this code
int[] ids = sResources.Split(',').Select(s => int.Parse(s)).ToArray();
rooms = from r in context.Rooms
where r.Area.Office.Id == officeId
&& r.MaximumPeople >= numberOfPeople
&& r.RoomResources.Any(s => ids.Contains(s.ResourceId))
select r;
but it return Room1 and Room2 and the result should be Room1
Maybe this?
int[] ids = sResources.Split(',').Select(s => int.Parse(s)).ToArray();
rooms = from r in context.Rooms
where r.Area.Office.Id == officeId
&& r.MaximumPeople >= numberOfPeople
&& ids.All(i => r.RoomResources.Any(s => s.ResourceId == i)) // try this here
select r;

entity framework distinct by field

i have table kopija that goes like this:
idKopija | idFilm | nije_tu
1 | 1 | 0
2 | 1 | 0
3 | 1 | 1
4 | 2 | 1 and etc.
And i have query that goes like this:
var upit = from f in baza.films
join z in baza.zanrs on f.idZanr equals z.idZanr
join k in baza.kopijas on f.idFilm equals k.idFilm
select new
{
idFilm = f.idFilm,
nazivFilm = f.naziv,
nazivZanr = z.naziv,
idZanr = f.idZanr,
godina = f.godina,
slika = f.slika,
klip = f.klip,
nijeTu = k.nije_tu
};
if (checkBox1.Checked)
upit = upit.Where(k => k.nijeTu == 0).Distinct();
else
{
upit = upit.Where(k => k.nijeTu == 0 || k.nijeTu == 1).Distinct();
}
Now i want to make a distinct list of "idFilm". But prolem is that I get idFilm on two places because one of them has nije_tu=0 and other one has nije_tu=1.
Please someone help me.
Thank you.
What about
upit.Where(k => k.nijeTu == 0 || k.nijeTu == 1).Select(x => x.idFilm).Distinct();
?

LINQ - Left Outer Join with multiple parameters in Where clause

How can I do this SQL query in LINQ:
select * from chat c
left outer join lead s on c.key = s.id
where (typeId = 5 AND c.key = #clientId) OR (c.typeId = 4 AND s.clientId = #clientId)
Or this SQL query -- Same, same
select * from chat c
where (typeId = 5 AND c.key = #clientId) OR (typeId = 4 AND c.key in (select id from lead where clientId = #clientId))
What I have:
var chatter = (from chat in linq.Chat
join lead in linq.Lead
on chat.key equals lead.Id.ToString() into clientLeads
from cl in clientLeads.Where(l => l.clientId == clientId).DefaultIfEmpty()
where (chat.typeId == 5 && chat.key == clientId.ToString()) ||
(chat.typeId == 4 && chat.key == cl.Id.ToString())
select chat).WithPath(prefetchPath).OrderByDescending(c => c.CreatedDate);
The above LINQ query doesn't yeild any results from the latter WHERE clause, what am I missing?
I translated the second query to linq:
var leadIds = linq.Lead.Where(l => l.clientId == clientId.ToString()).Select(l => l.id);
var chatter = from chat in linq.Chat
where (chat.typeId == 5 && chat.key == clientId.ToString()) ||
(chat.typeId == 4 && leadIds.Contains(chat.key));