Oracle Query don't see what's wrong - oracle

I am trying to run this Query but somehow the bottom part Label B doesn't work.
I am new to oracle and I just don't see what's wrong. Can anyone Please Help me? It would be much appreciated.
Its not returning any data when a salesperson is not tied to it. This should still return the information about the base customer regardless.
SELECT DISTINCT X.ship_sales_representative_id,
X.ship_sales_representative_name,
X.ship_sales_regional_name,
X.ship_sales_regional_head,
B.bl_customer_representative_id,
X.sp_customer_representative_id,
B.bill_customer_id,
X.ship_customer_id,
B.bill_customer_address_suffix,
X.ship_customer_address_suffix,
B.bill_customer_name,
X.ship_customer_name,
B.bill_customer_address,
X.ship_customer_address,
B.bill_customer_city,
X.ship_customer_city,
B.bill_customer_statecode,
X.ship_customer_statecode,
B.bill_customer_zipcode,
X.ship_customer_zipcode,
B.bill_customer_phonenumber,
X.ship_customer_phonenumber,
B.bill_customer_faxnumber,
X.ship_customer_faxnumber,
B.bill_customer_email,
X.ship_customer_email,
B.bill_customer_contact,
X.ship_customer_contact
FROM (SELECT DISTINCT S.rep_id Ship_Sales_Representative_ID,
S.rep_name Ship_Sales_Representative_Name,
S.reg_name Ship_Sales_Regional_Name,
S.reg_head Ship_Sales_Regional_Head,
C.rep_id Sp_Customer_Representative_ID,
C.cust_id Ship_Customer_ID,
C.addr_suffix Ship_Customer_Address_Suffix,
C.name Ship_Customer_Name,
C.addr_ln_1 Ship_Customer_Address,
C.city Ship_Customer_City,
C.state_cd Ship_Customer_StateCode,
C.zip_cd Ship_Customer_Zipcode,
C.phone_nbr Ship_Customer_PhoneNumber,
C.fax_nbr Ship_Customer_FaxNumber,
C.email Ship_Customer_Email,
C.contact Ship_Customer_Contact
FROM mdw.customer C,
mdw.sales_org S
WHERE C.rep_id = To_char(S.rep_id, 'FM000000')
AND C.cust_id = v_cust_id
AND C.addr_suffix = v_addr_suffix) X,
(SELECT DISTINCT C.rep_id Bl_Customer_Representative_ID,
C.cust_id Bill_Customer_ID,
C.addr_suffix Bill_Customer_Address_Suffix,
C.name Bill_Customer_Name,
C.addr_ln_1 Bill_Customer_Address,
C.city Bill_Customer_City,
C.state_cd Bill_Customer_StateCode,
C.zip_cd Bill_Customer_Zipcode,
C.phone_nbr Bill_Customer_PhoneNumber,
C.fax_nbr Bill_Customer_FaxNumber,
C.email Bill_Customer_Email,
C.contact Bill_Customer_Contact
FROM mdw.customer C
WHERE C.cust_id = v_cust_id
AND C.addr_suffix = '0001') B;

You probably want to add at the end of the query:
WHERE X.REP_ID = B.REP_ID
(and remove the first DISTINCT) or another condition for the JOIN otherwise this query is going to return all the combinations of records in X with records in B
Since you're looking for
AND C.CUST_ID =v_Cust_ID
you should use it in the join!
Since you're not sure that the information exists in X you should use a LEFT JOIN on X which you can do in Oracle by:
WHERE B.CUST_ID = X.CUST_ID(+)

Related

How to solve this Error in Linq : Operator '!=' cannot be applied to operands of type 'int' and 'System.Linq.IQueryable<int>'

var ll = from a in db.EmployeeMasters
where a.EmployeeID != (from d in db.EmployeeMasters
join c in db.PerformanceDetails on d.EmployeeID equals c.EmployeeID
join z in db.ProjectMasters on c.ProjectID equals z.ProjectID
into ss
from z in ss.DefaultIfEmpty()
where z.ProjectName == name || z.ProjectName == name1
select d.EmployeeID)
select a.EmployeeName;
It returns an error messages like below
Operator '!=' cannot be applied to operands of type 'int' and 'System.Linq.IQueryable'
I want to add this Linq query in http post method to view output in postman
Anyone Please help me to solve this
Actual question is select employees who are not part of 2 projects like (CRM, Automation)
Part of both project employees are in another project but some of the employees not in any projects
My Entity Framework Data Model is shown here:
name and name1 are given parameters for project names
You're making this much harder than necessary. In the first place, you should use these navigation properties EF kindly creates for you, instead of using verbose and error-prone join statements. Doing that, it's much easier to write a greatly simplified predicate:
var ll = from a in db.EmployeeMasters
where !a.PerformanceDetails
.Any(pd => pd.ProjectMaster.ProjectName == name
|| pd.ProjectMaster.ProjectName == name1)
select a.EmployeeName;
This is a different query --it translates into EXISTS-- but the result is the same and the query plan may even be better. Also, it's much easier to add more predicates to it later, if necessary.
Your question isn't really clear, but the error is pretty clear, you cannot compare type int and System.Linq.IQueryable<int>.
I assume your want something like this :
var ll = from a in db.EmployeeMasters
where !(from d in db.EmployeeMasters
join c in db.PerformanceDetails on d.EmployeeID equals c.EmployeeID
join z in db.ProjectMasters on c.ProjectID equals z.ProjectID
into ss
from z in ss.DefaultIfEmpty()
where z.ProjectName == name || z.ProjectName == name1
select d.EmployeeID).Contains(a.EmployeeID)
select a.EmployeeName;
Here we're looking for EmployeeIDs that do not appear in your query result.
int[] EmployeeIDs = (from em in db.EmployeeMasters
join pd in db.PerformanceDetails on em.EmployeeID equals pd.EmployeeID into pdRes
from pdResult in pdRes.DefaultIfEmpty()
join pm in db.ProjectMasters on pdResult.ProjectID equals pm.ProjectID into pmRes
from pmResult in pmRes.DefaultIfEmpty()
where (pmResult.ProjectName == "Automation" || pmResult.ProjectName == "CRM Customer")
select em.EmployeeID
).Distinct().ToArray();
var empResult = (from em in db.EmployeeMasters
where !EmployeeIDs.Contains(em.EmployeeID)
select new
{
EmployeeName = em.EmployeeName
}).ToList();

Oracle: Limiting a join with a 'many' table to just one instance?

This query returns a wide table containing horse-race results. However, one horse has multiple trainers and so this join is returning the same race-result for each trainer the horse has. How do I work around this? I've been playing around with Group By but Oracle doesn't seem to like it.
SELECT
b.meet_name AS Course,
a.race_time AS Time,
(f.jf_name||' '||f.jl_name) AS Jockey,
e.horse_name AS Horse,
c.odds,
d.place,
d.race_comment AS Note,
(g.bf_name||' '||g.bl_name) AS Breeder,
(h.tf_name||' '||h.tl_name) AS Trainer,
a.race_type AS Type,
a.distance AS Furlongs,
a.prize_money AS "Prize Money",
a.ground AS Ground
FROM proj_race_details a
JOIN proj_meet b ON a.meet_id = b.meet_id
JOIN proj_entry c ON c.race_id = a.race_id
JOIN proj_results d ON d.race_id = c.race_id AND d.horse_id = c.horse_id
JOIN proj_horses e ON e.horse_id = d.horse_id
JOIN proj_jockey f ON f.jockey_id = d.jockey_id
JOIN proj_breeder g ON g.breeder_id = e.breeder_id
JOIN proj_trainer h ON h.trainer_id = e.trainer_id;
EDIT:
This query would select only one trainer per horse. The trainer's name would be the first one, sorted alphabetically.
SELECT
b.meet_name AS Course,
a.race_time AS Time,
(f.jf_name||' '||f.jl_name) AS Jockey,
e.horse_name AS Horse,
c.odds,
d.place,
d.race_comment AS Note,
(g.bf_name||' '||g.bl_name) AS Breeder,
h.Trainer,
a.race_type AS Type,
a.distance AS Furlongs,
a.prize_money AS "Prize Money",
a.ground AS Ground
FROM proj_race_details a
JOIN proj_meet b ON a.meet_id = b.meet_id
JOIN proj_entry c ON c.race_id = a.race_id
JOIN proj_results d ON d.race_id = c.race_id AND d.horse_id = c.horse_id
JOIN proj_horses e ON e.horse_id = d.horse_id
JOIN proj_jockey f ON f.jockey_id = d.jockey_id
JOIN proj_breeder g ON g.breeder_id = e.breeder_id
JOIN
(SELECT ph.horse_id AS horse_id, MIN(pj.tf_name||' '||pj.tl_name) AS Trainer
FROM proj_trainer pj INNER JOIN proj_horses ph
ON pj.trainer_id = ph.trainer_id
GROUP BY ph.horse_id
) h
ON h.horse_id = e.horse_id;

Outer Join statement in LINQ

I am trying to create an outer join statement in LINQ and am not having much luck. I know that Performing an outer join requires two steps:
(1) Convert the join into a group join with into
(2) Use DefaultIfEmpty() on the group to generate the null value you expect if the joined result set is empty.
I have been using this code as an example:
var query = (from p in dc.GetTable<Person>()
join pa in dc.GetTable<PersonAddress>() on p.Id equals pa.PersonId into tempAddresses
from addresses in tempAddresses.DefaultIfEmpty()
select new { p.FirstName, p.LastName, addresses.State });
So I tried to do this:
var outerJoin =
from h in resultHours
join u in results on h.Key equals u.Key into outer
from dictionary in outer.DefaultIfEmpty()
select new {
The problem is that intellisense doesn't recognize anything in the select new {} statement. I've tried u. and h., even dictionary.
The problem I may be running into is that I'm trying to outer join two dictionaries. It doesn't seem to like that, although this is what I was told I need to do. I am obviously doing something wrong or not understanding something.
I need to join the dictionary results.Unit with the dictionary resultHours.Hours because my output is missing unitId fields under certain conditions. Doing an outer join is supposed to clear this up.
Here is the code for results:
var results =
(from v in VDimUnit
join vf in VFactEnergyAllocation on v.UnitKey equals vf.UnitKey
join vd in VDimGadsEvent on vf.GadsEventKey equals vd.GadsEventKey
join vt in VDimTime on vf.TimeKey equals vt.TimeKey
where typeCodes.Contains(vd.GadsEventTypeCode)
&& vt.YearNum >= (year - 3) && vt.YearNum <= year
group vf by new {v.PlantId, v.PhysicalUnitId, v.NetDependableCapacity, v.NetMaximumCapacity,
vt.MonthNum} into groupItem
select new {groupItem.Key.PlantId, groupItem.Key.PhysicalUnitId, groupItem.Key.NetMaximumCapacity,
groupItem.Key.MonthNum, PO_HRS = groupItem.Sum(
x=> (float)x.AllocatedEnergyMwh / groupItem.Key.NetDependableCapacity),
UO_HRS = groupItem.Sum(x=> (float)x.AllocatedEnergyMwh / groupItem.Key.NetDependableCapacity),
Unit = groupItem.Count(), groupItem.Key}).ToDictionary(x=> x.Key, x=> x);
Here is the code for resultHours:
var resultHours =
(from vt in VDimTime
join vf in VFactEnergyAllocation on vt.TimeKey equals vf.TimeKey
join vd in VDimGadsEvent on vf.GadsEventKey equals vd.GadsEventKey
join v in VDimUnit on vf.UnitKey equals v.UnitKey
group vt by new {v.PlantId, v.PhysicalUnitId, v.NetDependableCapacity, v.NetMaximumCapacity,
vt.MonthNum} into groupItem
select new {groupItem.Key.PlantId, groupItem.Key.PhysicalUnitId, groupItem.Key.NetMaximumCapacity,
Hours = groupItem.Count(), groupItem.Key}).ToDictionary(x=> x.Key.ToString(), x=> x.Hours);
This is presently how I have my output. It will change after I figure out how to do the outer join.
var finalResults =
(from r in results
orderby r.Key.MonthNum, r.Key.PlantId, r.Key.PhysicalUnitId
select new {Site = r.Key.PlantId, Unit = r.Key.PhysicalUnitId, r.Key.MonthNum, Numerator = r.Value.PO_HRS, Denominator =
resultHours[r.Key.ToString()], Weight = r.Key.NetMaximumCapacity, Data_Indicator = DATA_INDICATOR,
Budgeted = budgetedPlannedOutageHrs, Industry_Benchmark = INDUSTRY_BENCHMARK, Comments = comments,
Executive_Comments = executiveComments, Fleet_Exec_Comments = fleetExecComments});
I'm at a loss. The LINQ outer join examples I have found apaprently do not apply when joining dictionaries.

Greater Than Condition in Linq Join

I had tried to join two table conditionally but it is giving me syntax error. I tried to find solution in the net but i cannot find how to do conditional join with condition. The only other alternative is to get the value first from one table and make a query again.
I just want to confirm if there is any other way to do conditional join with linq.
Here is my code, I am trying to find all position that is equal or lower than me. Basically I want to get my peers and subordinates.
from e in entity.M_Employee
join p in entity.M_Position on e.PostionId >= p.PositionId
select p;
You can't do that with a LINQ joins - LINQ only supports equijoins. However, you can do this:
var query = from e in entity.M_Employee
from p in entity.M_Position
where e.PostionId >= p.PositionId
select p;
Or a slightly alternative but equivalent approach:
var query = entity.M_Employee
.SelectMany(e => entity.M_Position
.Where(p => e.PostionId >= p.PositionId));
Following:
from e in entity.M_Employee
from p in entity.M_Position.Where(p => e.PostionId >= p.PositionId)
select p;
will produce exactly the same SQL you are after (INNER JOIN Position P ON E..PostionId >= P.PositionId).
var currentDetails = from c in customers
group c by new { c.Name, c.Authed } into g
where g.Key.Authed == "True"
select g.OrderByDescending(t => t.EffectiveDate).First();
var currentAndUnauthorised = (from c in customers
join cd in currentDetails
on c.Name equals cd.Name
where c.EffectiveDate >= cd.EffectiveDate
select c).OrderBy(o => o.CoverId).ThenBy(o => o.EffectiveDate);
If you have a table of historic detail changes including authorisation status and effective date. The first query finds each customers current details and the second query adds all subsequent unauthorised detail changes in the table.
Hope this is helpful as it took me some time and help to get too.

How to implement a left outer join in the Entity Framework

I have the following SQL query:-
select distinct * from dbo.Profiles profiles
left join ProfileSettings pSet on pSet.ProfileKey = profiles.ProfileKey
left join PlatformIdentities pId on pId.ProfileKey = profiles.Profilekey
I need to convert it to a LinqToEntities expression. I have tried the following:-
from profiles in _dbContext.ProfileSet
let leftOuter = (from pSet in _dbContext.ProfileSettingSet
select new
{
pSet.isInternal
}).FirstOrDefault()
select new
{
profiles.ProfileKey,
Internal = leftOuter.isInternal,
profiles.FirstName,
profiles.LastName,
profiles.EmailAddress,
profiles.DateCreated,
profiles.LastLoggedIn,
};
The above query works fine because I haven't considered the third table "PlatformIdentities". Single left outer join works with what I have done above. How do I include PlatformIdentities (the 3rd table) ? I basically want to translate the SQL query I specified at the beginning of this post (which gives me exactly what I need) in to LinqToEntities.
Thanks
Let me know if you want to select something different, but a true join is below
from p in _dbContext.ProfileSet
join ps in _dbContext.ProfileSettings on p.ProfileKey = ps.ProfileKey into a
join pi in _dbContext.PlatformIdentities on p.ProfileKey = pi.ProfileKey into b
select new
{
profiles.ProfileKey,
profiles.FirstName,
profiles.LastName,
profiles.EmailAddress,
profiles.DateCreated,
profiles.LastLoggedIn,
PlatformSettings = a.Select(x=>x),
PlatformIdentities = b.Select(y=>y)
}

Resources