SQL query to fetch count on the association tables - sql

I'm trying to write the following SQL Server query, where I also need to fetch the count of vehicleId that is being referred in the child table,
select
BV.[BaseVehicleId], BV.[MakeId], MK.[MakeName], BV.[ModelId],
MD.[ModelName], V.[VehicleId], V.[SubModelId], SubMD.[SubModelName],
V.[RegionId], V.PublicationStageId,
V.[LastUpdateDate], V.[InsertDate], V2BedCount, V2BodyCount,
V2BrakeCount, V2DriveCount, V2EngineCount,V2MfrCount, V2SpringCount,
V2SteeringCount, V2TransmissionCount, V2WheelCount
from
[dbo].[BaseVehicle] BV,
[dbo].[Make] MK,
[dbo].[Model] MD,
[dbo].[SubModel] SubMD,
[dbo].[VehicleToBedConfig] V2Bed,
[dbo].[VehicleToBodyStyleConfig] V2Body,
[dbo].[VehicleToBrakeConfig] V2Brake,
[dbo].[VehicleToDriveType] V2Drive,
[dbo].[VehicleToEngineConfig] V2Engine,
[dbo].[VehicleToMfrBodyCode] V2Mfr,
[dbo].[VehicleToSpringTypeConfig] V2Spring,
[dbo].[VehicleToSteeringConfig] V2Steering,
[dbo].[VehicleToTransmission] V2Transmission,
[dbo].[VehicleToWheelBase] V2Wheel,
[dbo].[Vehicle] V
where
V.[PublicationStageId] = '4'
and V.[DeleteDate] IS NULL
and BV.[BaseVehicleId] = V.[BaseVehicleId]
and MK.[MakeId] = BV.[MakeId]
and MD.[ModelId] = BV.[ModelId]
and V.[SubModelId] = SubMD.[SubModelId]
and V.[VehicleId] = V2Bed.[VehicleId]
and V.[VehicleId] = V2Body.[VehicleId]
and V.[VehicleId] = V2Brake.[VehicleId]
and V.[VehicleId] = V2Drive.[VehicleId]
and V.[VehicleId] = V2Engine.[VehicleId]
and V.[VehicleId] = V2Mfr.[VehicleId]
and V.[VehicleId] = V2Spring.[VehicleId]
and V.[VehicleId] = V2Steering.[VehicleId]
and V.[VehicleId] = V2Transmission.[VehicleId]
and V.[VehicleId] = V2Wheel.[VehicleId]
I'm looking for a way to push the details on these columns from the above query:
V2BedCount, V2BodyCount, V2BrakeCount,
V2DriveCount, V2EngineCount,
V2MfrCount, V2SpringCount, V2SteeringCount, V2TransmissionCount,
V2WheelCount
Here V2BedCount is the count of Vehicle ID's that are mapped with VehicleToBedConfig table like
select COUNT(VehicleId) V2BedCount
from VehicleToBedConfig
group by VehicleId
Please let me know how do I insert the second query in the first to have one query populate the count details for all these columns
V2BedCount, V2BodyCount, V2BrakeCount,
V2DriveCount, V2EngineCount,
V2MfrCount, V2SpringCount, V2SteeringCount, V2TransmissionCount,
V2WheelCount

Assuming Id is a PK in VehicleToBedConfig try
COUNT(DISTINCT V2Bed.Id) OVER(PARTITION BY V.VehicleId) V2BedCount,
...
I advice you use an explicit JOIN syntax.

Related

How to write join query with multiple column - LINQ

I have a situation where two tables should be joined with multiple columns with or condition. Here, I have a sample of sql query but i was not able to convert it into linq query.
select cm.* from Customer cm
inner join #temp tmp
on cm.CustomerCode = tmp.NewNLKNo or cm.OldAcNo = tmp.OldNLKNo
This is how i have write linq query
await (from cm in Context.CustomerMaster
join li in list.PortalCustomerDetailViewModel
on new { OldNLKNo = cm.OldAcNo, NewNLKNo = cm.CustomerCode } equals new { OldNLKNo = li.OldNLKNo, NewNLKNo = li.NewNLKNo }
select new CustomerInfoViewModel
{
CustomerId = cm.Id,
CustomerCode = cm.CustomerCode,
CustomerFullName = cm.CustomerFullName,
OldCustomerCode = cm.OldCustomerCode,
IsCorporateCustomer = cm.IsCorporateCustomer
}).ToListAsync();
But this query doesn't returns as expected. How do I convert this sql query into linq.
Thank you
You didn't tell if list.PortalCustomerDetailViewModel is some information in the database, or in your local process. It seems that this is in your local process, your query will have to transfer it to the database (maybe that is why it is Tmp in your SQL?)
Requirement: give me all properties of a CustomerMaster for all CustomerMasters where exists at least one PortalCustomerDetailViewModel where
customerMaster.CustomerCode == portalCustomerDetailViewModel.NewNLKNo
|| customerMaster.OldAcNo == portalCustomerDetailViewModel.OldNLKNo
You can't use a normal Join, because a Join works with an AND, you want to work with OR
What you could do, is Select all CustomerMasters where there is any PortalCustomerDetailViewModel that fulfills the provided OR:
I only transfer those properties of list.PortalCustomerDetailViewModel to the database that I need to use in the OR expression:
var checkProperties = list.PortalCustomerDetailViewModel
.Select(portalCustomerDetail => new
{
NewNlkNo = portalCustomerDetail.NewNlkNo,
OldNLKNo = portalCustomerDetail.OldNLKNo,
});
var result = dbContext.CustomerMasters.Where(customerMaster =>
checkProperties.Where(checkProperty =>
customerMaster.CustomerCode == checkProperty.NewNLKNo
|| customerMaster.OldAcNo == checkProperty.OldNLKNo)).Any()))
.Select(customerMaster => new CustomerInfoViewModel
{
Id = customerMaster.Id,
Name = customerMaster.Name,
...
});
In words: from each portalCustomerDetail in list.PortalCustomerDetailViewModel, extract the properties NewNKLNo and OldNLKNo.
Then from the table of CustomerMasters, keep only those customerMasters that have at least one portalCustomerDetail with the properties as described in the OR statement.
From every remaining CustomerMasters, create one new CustomerInfoViewModel containing properties ...
select cm.* from Customer cm
inner join #temp tmp
on cm.CustomerCode = tmp.NewNLKNo or cm.OldAcNo = tmp.OldNLKNo
You don't have to use the join syntax. Adding the predicates in a where clause could get the same result. Try to use the following code:
await (from cm in Context.CustomerMaster
from li in list.PortalCustomerDetailViewModel
where cm.CustomerCode == li.NewNLKNo || cm.OldAcNo = li.OldNLKNo
select new CustomerInfoViewModel
{
CustomerId = cm.Id,
CustomerCode = cm.CustomerCode,
CustomerFullName = cm.CustomerFullName,
OldCustomerCode = cm.OldCustomerCode,
IsCorporateCustomer = cm.IsCorporateCustomer
}).ToListAsync();
var result=_db.Customer
.groupjoin(_db.#temp ,jc=>jc.CustomerCode,c=> c.NewNLKNo,(jc,c)=>{jc,c=c.firstordefault()})
.groupjoin(_db.#temp ,jc2=>jc2.OldAcNo,c2=> c2.OldNLKNo,(jc2,c2)=>{jc2,c2=c2.firstordefault()})
.select(x=> new{
//as you want
}).distinct().tolist();

I need to transform a SQL query with inner joins to Linq in Entity Framework

I am very new to translating queries to entity, I don't know how to replace that query into linq in my code
select
brules.rule_description, brules.user_story_number,
so.source_name,
count(dlog.row_id) as error_count,
cast(execution_date as date) as execution_date
from
br.lk_business_rules brules
inner join
br.business_rules_detailed_log dlog on dlog.user_story_number = brules.user_story_number
inner join
br.lk_business_rules_source so on so.source_id = source_id_fk
where
brules.status_id_fk = 3
group by
brules.rule_description, brules.user_story_number,
so.source_name, cast(execution_date as date)
order by
brules.rule_description
i tried this:
var query = from br in _context.Lk_business_rules
join detLog in _context.Business_rules_detailed_log
on br.User_story_number equals detLog.User_story_number
join source in _context.Lk_business_rules_source
on detLog.Source_id equals source.Source_id
where br.Status_id_fk == 3
select new
{
Business_rule_description = br.Rule_description,
Business_rule_storynumber = br.User_story_number,
Source = source.Source_name,
Error_count = detLog.Row_id.Count,
Date = detLog.Execution_date
};
but not succed

Nhibernate Criteria retrieve child of parent with restriction on other child of parent

I need to be able to write the following query as a Criteria.
SELECT hist.*
FROM
Administration admin
INNER JOIN Item item ON item.AdministrationId = admin.AdministrationId
INNER JOIN ItemHistory hist ON hist.ItemId = item.ItemId
WHERE
item.itemId = #param
and hist.IsError =
(
SELECT (CASE status.errorType
WHEN 'Warning' THEN 0
ELSE 1
END
)
FROM
AdminStatus status
WHERE
status.AdministrationId = admin.AdministrationId
AND status.Group = 'Issues'
)
I'm pretty sure I'll need to do the sub query as a detached criteria:
var status = DetachedCriteria.For<AdminStatus>("status");
status.CreateAlias("status.Administration", "admin");
status.Add(Restrictions.Eq("status.Group", "Issues"));
status.SetProjection(Projections.Property("AdministrationId"));
status.SetProjection(Projections.Conditional(
Restrictions.Eq("status.errorType", "Warning"),
Projections.Constant(0),
Projections.Constant(1)));
But I'm not sure how to join that with my primary criteria:
var criteria = Session.CreateCriteria<ItemHIstory>("hist");
criteria.CreateAlias("ItemHistory.Item", "item");
criteria.CreateAlias("item.Administration", "admin");
But I'm not sure how to join that with my primary criteria:
Methods from Subqueries class glue detached sub-query with main criteria. Subqueries.PropertyEq in you case:
var criteria = Session.CreateCriteria<ItemHIstory>("hist");
criteria.CreateAlias("ItemHistory.Item", "item");
criteria.CreateAlias("item.Administration", "admin");
criteria.Add(Subqueries.PropertyEq("hist.IsError ", status))
And regarding detached criteria. Alias creation seems unnecessary:
var status = DetachedCriteria.For<AdminStatus>("status");
status.Add(Restrictions.EqProperty("status.AdministrationId", "admin.AdministrationId"));
status.Add(Restrictions.Eq("status.Group", "Issues"));
status.SetProjection(Projections.Conditional(
Restrictions.Eq("status.errorType", "Warning"),
Projections.Constant(0),
Projections.Constant(1)));

Problems with Left join Query LinqToSql

IBookingRepository bookingResp = new BookingRepository();
IQueryable<bookingTest> bookings = bookingResp.GetAllBookingsByView();
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = from booking in bookings
join f in getallAttendees on booking.UserID equals f.UserID into fg
from fgi in fg.DefaultIfEmpty() //Where(f => f.EventID == booking.EventID)
where
booking.EventID == id
select new
{
EventID = booking.EventID,
UserID = booking.UserID,
TrackName = booking.Name,
BookingStatus = booking.StatusID,
AttendeeName = booking.FirstName,
// name = account.FirstName,
AmountPaid = booking.Cost,
AttendeeAddress = booking.DeliveryAdd1,
City = booking.DeliveryCity,
Postcode = booking.Postcode,
Date = booking.DateAdded,
hel = fgi == null ? null : fgi.HelmetsPurchased }// Product table
Hi, the above query doesnt executes it gives an error: The specified LINQ expression contains references to queries that are associated with different contexts. Any one can spot the what the problem is with the query.
I think that your getAllAttendees is from a different context than bookings so you won't be able to join them. To give a more exact answer you need to show where bookings and getAllAttendees comes from.

How do i transform a HQL result to List<T> where T is a mapped class

I have this nhibernate query:
var q =
NHibernateSession.Current.CreateSQLQuery
(
#"SELECT LastestEvents.*
FROM (
SELECT DISTINCT SbQcontainer.Container
FROM HistoricEvents
SbQcontainer WHERE SbQcontainer.LineCompany_Id = :lineCompany) as Sbq
JOIN HistoricEvents as LastestEvents
ON LastestEvents.id = (
SELECT TOP(1) id
FROM HistoricEvents mi
WHERE mi.Container = Sbq.Container and mi.LineCompany_Id = :lineCompany
ORDER BY mi.Date DESC
)"
).SetResultTransformer(Transformers.AliasToBean(typeof(HistoricEvent)));
q.SetParameter("lineCompany",lineCompany.Id);
q.SetCacheable(false);
var results = q.List<HistoricEvent>().ToList();
It looks for the lastest events on each container for the given lineCompany, it works, but i dont know how to set this resultset to a list of T HistoricEvent, i try this line:
.SetResultTransformer(Transformers.AliasToBean(typeof(HistoricEvent)));
But throws NHibernate.PropertyNotFoundException:Could not find a setter for property 'Event_Id' in class 'HistoricEvent'.
Is there any way to do this?, or maybe doing this same query using the ICriteria API?
Thx in advance.
Assuming HistoricEvent is a mapped entity, the following should give you what you're looking for:
var q =
NHibernateSession.Current.CreateSQLQuery
(
#"SELECT LastestEvents.*
FROM (
SELECT DISTINCT SbQcontainer.Container
FROM HistoricEvents
SbQcontainer WHERE SbQcontainer.LineCompany_Id = :lineCompany) as Sbq
JOIN HistoricEvents as LastestEvents
ON LastestEvents.id = (
SELECT TOP(1) id
FROM HistoricEvents mi
WHERE mi.Container = Sbq.Container and mi.LineCompany_Id = :lineCompany
ORDER BY mi.Date DESC
)"
).AddEntity(typeof(HistoricEvent));
q.SetParameter("lineCompany",lineCompany.Id);
q.SetCacheable(false);
var results = q.List<HistoricEvent>().ToList();
See the relevant documentation for further details.