I have 3 tables in my Database
and i want to retrieve all products with their quantity from bill_Details tables.
This is the query:
SELECT p.prod_Id,p.prod_Name,COALESCE(sum(b.de_Quantity+b.de_Bonus),0)
,p.prod_Cost,p.prod_ExpDate,p.prod_BonusInfo,p.prod_Note
FROM (products p
LEFT JOIN bill_Details b
ON p.prod_Id=b.prod_Id)
LEFT JOIN bills a
ON b.bill_Id = a.bill_Id and a.cus_Sup=1 and a.archived=0
GROUP BY p.prod_Id, p.prod_Name,p.prod_Cost,p.prod_ExpDate,p.prod_BonusInfo,
p.prod_Note
ORDER BY p.prod_Name asc
The issue is that this query retrieve the same quantity when a.cus_Sup=1 or a.cus_Sup=0 !
Knowing that when a.cus_Sup=0 quantity should be 0 , and when a.cus_Sup=1 it's 29.5 for a specific product.
This is the data:
Below Query works for your case.
SELECT p.prod_id,
p.prod_name,
COALESCE(Sum(b.de_quantity + b.de_bonus), 0),
p.prod_cost,
p.prod_expdate,
p.prod_bonusinfo,
p.prod_note
FROM products p
LEFT JOIN (SELECT bd.*
FROM bill_details bd
JOIN bills a
ON bd.bill_id = a.bill_id
WHERE a.cus_sup = 1
AND a.archived = 0) b
ON p.prod_id = b.prod_id
GROUP BY p.prod_id,
p.prod_name,
p.prod_cost,
p.prod_expdate,
p.prod_bonusinfo,
p.prod_note
ORDER BY p.prod_name ASC
Related
I'm trying to do Linq group by query with a left join count:
from region in context.Regions
join person in context.Persons on region.Id equals person.RegionId into persons
from personNullable in persons.DefaultIfEmpty()
group personNullable by region.Name into g
select new { g.Key, Members = g.Count(r => r != null) }
Result:
[Name], [Members]
AAA 0
BBB 2
CCC 1
But this query translated to SQL without grouping and select all of the columns from both tables (which is not needed):
SELECT [region0].[ID], [region0].[DateChanged], [region0].[UsrIDChanged], [region0].[DateCreated], [region0].[UsrIDCreated], [region0].[IsDefault], [region0].[Name], [region0].[ParentRegionID], [person0].[ID], [person0].[Street], [person0].[LastName], [person0].[LastVisitDate], [person0].[Age], [person0].[Name], [person0].[RegionID]
FROM [Regions] AS [region0]
LEFT JOIN [Persons] AS [person0] ON [region0].[ID] = [person0].[RegionID]
ORDER BY [region0].[ID]
GO
Is this possible to select only needed columns or do a native group by query similar to this:
SELECT r.Name, COUNT(p.Id) AS Memebers
FROM Region AS r
LEFT JOIN Person AS p ON r.Id = p.Region
GROUP BY r.Name
basically i have 3 tables and those are user,colors and usercolor
tables info
User Tables has fields like -> UserID, UserName
Color Tables has fields like -> ColorID, ColorName
UserColor Tables has fields like -> UserID, ColorID
i have corresponding dbset classes in my code.
now see the below query where left join is performed among 3 tables in sql and tell me how to write the same equivalent query with EF and LINQ.
select c.ColorID
, c.ColorName
, IsSelected = case when uc.ColorID is null then 0 else 1 end
from dbo.Colors c
left join dbo.UserColor uc on uc.ColorID = c.ColorID and uc.UserID = 1 --leave this in the join or it becomes an inner join
left join dbo.Users u on u.UserID = uc.UserID
You can try as shown below.
var result = from c in dbo.Colors
join uc in dbo.UserColor on (uc.ColorID = c.ColorID and uc.UserID = 1) into UserColor
from q in UserColor.DefaultIfEmpty() join u in dbo.Users
on q.UserID equals u.UserID into Users
from l in Users.DefaultIfEmpty()
select new
{
ColorID = c.ColorID,
ColorName = c.ColorName,
IsSelected = uc.ColorID == null ? 0 : 1
};
You can read more about Left Outer Join in LINQ to Entities
I need a query that select customer table with right cardId by applied the below cases.
If you have any suggestions, please share.
Possible cases are:
Only one records found - easy, use the Card_id found
No records found - leave blank
More than one record found - use the Card_id that starts with 2000 if available, otherwise pick the one with latest created date (in CustomerCards table)
Customer Table:
ID CardID
1 200132
2 263987
3 100789
..
CustomerCards table
CustomerId CardID CreatedOn
1 209890 12/11/2014
1 200132 12/12/2014
1 100732 11/10/2014
2 168902 12/11/2014
2 263987 15/01/2015
I've started with left join:
select ct.* from dbo.Customer ct
left join dbo.CustomerCard cc
on ct.id = cc.customerId
And a bit stuck after that.
A start
;with cte1 as
(
select cc.CustomerId, cc.CardID, cc.CreatedOn
from dbo.CustomerCard cc
group by cc.CustomerId, cc.CardID, cc.CreatedOn
having count(*) = 1
), cte200 as
(
select cc.CustomerId, cc.CardID, max(cc.CreatedOn)
from dbo.CustomerCard cc
group by cc.CustomerId, cc.CardID
where cc.CardID like '2000%'
)
select cte1
union
select cte2000
union
select ct.ID, ct.CardID, '1/1/1900' as CreatedOn
from dbo.Customer ct
left join dbo.CustomerCard cc
on ct.id = cc.customerId
where cc.customerId is null
union
select cc.ID, cc.CardID, max(cc.CreatedOn)
from dbo.CustomerCard cc
left join cte1
on cte1.customerId = cc.customerId
left join cte2000
on cte2000.customerId = cc.customerId
where cte1.customerId is null
and cte2000.customerId is null
group by cc.ID, cc.CardID
i am working on windows Form application and wanted to perform Paging in DataGridView
so i wrote a query for that
Select DISTINCT TOP(1000)
TblStudentBioData.RegNo
, Coalesce(TblStudentBioData.First_NameUr + SPACE(1) +
TblStudentBioData.Middle_NameUr + SPACE(1),TblStudentBioData.First_NameUr)
+ TblStudentBioData.Last_NameUr AS Name
, TblStudentBioData.Father_NameUr
, Coalesce(Ay.AcademicYearName,N'+#InCaseNull+') As AcademicYearName
, Coalesce(Smst.SemName,N'+#InCaseNull+') As SemName
, Coalesce(Colg.CollegeName,N'+#InCaseNull+') As CollegeName
, Coalesce(CID.ClassName,N'+#InCaseNull+') As ClassName
, TblImages.Images
, TblStudentBioData.Student_ID
, TblImages.ImageId
, Ay.AcademicYearId
, Smst.SemesterId
, TblClassSchedule.ClassSchId
FROM TblStudentBioData
INNER JOIN TBLCFGSEX AS sex
ON TblStudentBioData.CfgSexId = sex.CfgSexId
LEFT JOIN TBLMARITALSTATUS ms
ON TblStudentBioData.MaritalStatusId = ms.MaritalStatusId
INNER JOIN TblImages
ON TblStudentBioData.ImageId = TblImages.ImageId
LEFT JOIN TBLBLOODGROUP BG
ON TblStudentBioData.BloodID = BG.BloodId
LEFT JOIN TblStudentDetail
ON (TblStudentBioData.Student_ID = TblStudentDetail.Student_ID)
LEFT JOIN TblStudentSubAss
ON TblStudentDetail.StudentDetailID = TblStudentSubAss.StudentDetailID
LEFT JOIN TblClassSchedule
ON TblStudentDetail.CLassSchID = TblClassSchedule.ClassSchID
LEFT JOIN TblSubAss
ON TblSubAss.SubAssId = TblStudentSubAss.SubAssId
LEFT JOIN TblClass AS CID
ON TblClassSchedule.ClassID = CID.ClassID
LEFT JOIN TBLCOLLEGE Colg
ON CID.CollegeId = Colg.CollegeID
LEFT JOIN TblSemAssigning SA
ON TblClassSchedule.SemAssId = SA.SemAssId
LEFT JOIN TblAcademicYear AY
ON SA.AcademicYearId = AY.AcademicYearId
LEFT JOIN TblSemester Smst
ON Smst.SemesterId = SA.SemesterId
This Query Return me more than 28K rows but for paging i want only 1000 rows and total records which is 28K i will be fetching records 1000 wise.
Any Idea how can i do this ?
Note:
This query takes more then 20 seconds to execute and i wanted a solution which does not increase executing time.
If you only hava 1:1 detail-Tables in your query you could first do a selec count() on your primary key-field of your primary table. that should only last very few milliseconds
i have query like
SELECT distinct(a.CreatedOn),
a.id AS ID ,
u1.FirstName CreatedByFirstName,
u1.LastName
FROM AuditDetail a
LEFT JOIN UserProfile u1 ON a.CreatedBy = u1.UserProfileID
LEFT JOIN UserProfile u2 ON a.UpdatedBy = u2.UserProfileID
this shows me all the records. and distinct createdon also repeated in each records because all the records comming. i want that if the createdon is same in all the records then its first record or single record should come not all. where i'm wrong?
You can use Ranking Function such as ROW_NUMBER() which give rank on each record for every group.
WITH recordList
AS
(
SELECT a.CreatedOn,
a.id as ID ,
u1.FirstName CreatedByFirstName,
u1.LastName,
ROW_NUMBER() OVER(PARTITION BY a.CreatedOn ORDER BY a.CreatedOn) rn
FROM AuditDetail a
left join UserProfile u1
on a.CreatedBy = u1.UserProfileID
left join UserProfile u2
on a.UpdatedBy = u2.UserProfileID
)
SELECT CreatedOn,
ID,
CreatedByFirstName,
LastName
FROM recordList
WHERE rn = 1
Try this one,
Might will help you, used subquery
SELECT a.CreatedOn,
a.id AS ID ,
u1.FirstName CreatedByFirstName,
u1.LastName
FROM AuditDetail a
LEFT JOIN UserProfile u1 ON a.CreatedBy = u1.UserProfileID LEFT joinUserProfileu2 ON a.UpdatedBy = u2.UserProfileID
WHERE a.CreatedOn IN
(SELECT DISTINCT CreatedOn
FROM AuditDetail)