I have the following tables in this SQL database (some fields are irrelevant to this question):
I have the following LINQ query:
Dim trips = From tr In db.tbl_Trips _
Join ds In db.tbl_tripDeptStations On tr.trip_ID Equals ds.tds_ID _
Where ds.tbl_Station.stn_County = county _
And tr.trip_StartDate >= startDate _
And tr.trip_EndDate <= endDate _
Select tr.trip_Name, tr.trip_StartDate, tr.trip_EndDate, tr.trip_SmallImage, tr.tbl_TourOperator.tourOp_Name
startDate, endDate and county are variables which I have declared in code above (not shown).
I am trying to show trips which have certain departure stations associated, based upon the county which can be found in the station table.
However, when I run the query, I get no results, and no error messages.
I also have this SQL query which works correctly:
SELECT distinct t.trip_ID, t.trip_Name, t.trip_StartDate, toop.tourOp_Name
FROM tbl_Trip AS t
INNER JOIN
(SELECT tds.tds_trip
FROM tbl_tripDeptStation AS tds
INNER JOIN tbl_station AS s
ON tds.tds_Stn = s.stn_ID
WHERE s.stn_county = 'Greater London'
) AS ds
ON t.trip_ID = ds.tds_trip
INNER JOIN tbl_TourOperator AS toop ON t.tourOp_ID = toop.tourop_id
WHERE t.trip_StartDate >= #StartDate AND t.trip_EndDate <= #EndDate
ORDER BY t.trip_
Can anyone shed some light as to where I might be going wrong?
if you're using entity framework,
var ds = from tds in tbl_tripdeptstation
join s in tbl_station on tds.tds_stn equals s.stn_id
where s.stn_country.equals("somecountry")
select new {tds.trip};
var result = (from t in tbl_trip
join ds2 in ds on t.trip_id equals ds2.trip
join toop in tbl_touroperator on t.tourop_id equals toop.tourop_id
where t.trip_start >= SomeDate AND t.trip_enddate <= EndDate
select new { t.trip_ID, t.trip_Name, t.trip_StartDate, toop.tourOp_Name}).Distinct().OrderBy(r => r.trip_);
Related
I have three tables that I would like to select from
Table 1 has a bunch of static information about a user like their idnumber, name, registration date
Table 2 has the idnumber of the user, course number, and the date they registered for the course
Table 3 has the course number, and the title of the course
I am trying to use one query that will select the columns mentioned in table 1, with the most recent course they registered (name and date registered) as well as their first course registered (name and date registered)
Here is what I came up with
SELECT u.idst, u.userid, u.firstname, u.lastname, u.email, u.register_date,
MIN(l.date_inscr) as mindate, MAX(l.date_inscr) as maxdate, lc.coursename
FROM table1 u,table3 lc
LEFT JOIN table2 l
ON l.idCourse = lc.idCourse
WHERE u.idst = 12787
AND u.idst = l.idUser
And this gives me everything i need, and the dates are correct but I have no idea how to display BOTH of the names of courses. The most recent and the first.
And help would be great.
Thanks!!!
You can get your desired results by generating the min/max date_inscr for each user in a derived table and then joining that twice to table2 and table3, once to get each course name:
SELECT u.idst, u.userid, u.firstname, u.lastname, u.email, u.register_date,
l.mindate, lc1.coursename as first_course,
l.maxdate, lc2.coursename as latest_course
FROM table1 u
LEFT JOIN (SELECT idUser, MIN(date_inscr) AS mindate, MAX(date_inscr) AS maxdate
FROM table2
WHERE idUser = 12787
) l ON l.idUser = u.idst
LEFT JOIN table2 l1 ON l1.idUser = l.idUser AND l1.date_inscr = l.mindate
LEFT JOIN table3 lc1 ON lc1.idCourse = l1.idCourse
LEFT JOIN table2 l2 ON l2.idUser = l.idUser AND l2.date_inscr = l.maxdate
LEFT JOIN table3 lc2 ON lc2.idCourse = l2.idCourse
As #BillKarwin pointed out, this is more easily done using two separate queries.
Please see the tables:
Sub-Query Method:
select p.Name from Person p where p.PID in
(select mc.PID from M_Cast mc where mc.MID in
(select m.MID from Movie m where lower(title)='anand' ))
Even join is not working:
select p.Name
from Movie m
join M_Cast mc on m.MID = mc.MID
join Person p on mc.PID = p.PID
group by m.MID
having lower(m.title)='anand'
Your first query works without errors and if you make adjustments like in my few next steps the second one will work also.
Your second query: you can not select only p.Name and group by only m.MID. If it is in select clause and is not a part of aggregate function then you have to use it in group by clause. For example like this:
select p.Name
from Movie m
join M_Cast mc on m.MID = mc.MID
join Person p on mc.PID = p.PID
group by p.Name;
Your second query also has a HAVING clause having lower(m.title)='anand' but it should be in where clause like this:
select p.Name
from Movie m
join M_Cast mc on m.MID = mc.MID
join Person p on mc.PID = p.PID
where lower(m.title)='anand'
group by p.Name;
Now that both query are working you need to check if you have a movie with title 'ANAND' in your data. Also you need to check if you have a corresponding MID and PID data in other tables.
I have tested this in MySQL but it will maybe help you even if you use other database to guide you through some mistakes... Here is a small DEMO in MySQL where you will see that data will not be returned if there is no data in one table.
Here is a small DEMO for SQLite where you can see that your first query is working:
http://sqlfiddle.com/#!7/3ec44/1
and here is a small DEMO where you can see that my code is working:
http://sqlfiddle.com/#!7/3ec44/2
Please check the data!
After I have exchanged few comments with OP I have noticed that maybe it is a blank space in data making a problem. So I suggested this:
select p.Name
from Person p
where trim(p.PID, ' ') in (select trim(mc.PID, ' ')
from M_Cast mc
where mc.MID in (select m.MID
from Movie m
where lower(title)='anand'))
This also can be implemented in the second query:
select p.Name
from Movie m
join M_Cast mc on m.MID = mc.MID
join Person p on trim(mc.PID, ' ') = trim(p.PID, ' ')
where lower(m.title)='anand'
group by p.Name;
The problem was that in the query two tables were joined with mc.PID = p.PID and one column had data with blank spaces. So the query was trying to join this data : ' 1' = '1'. TRIM function will remove all the blank spaces in the value and join will then be possible.
SELECT MOVIE.title, person.name
FROM (MOVIE INNER JOIN mcast ON MOVIE.MID = mcast.MID) INNER JOIN person ON mcast.PID = person.PID
WHERE (((MOVIE.title)="ANAND"));
select distinct p.name [Actors in Anand]
Movie m
join M_Cast mc on mc.MID=m.MID
join Person p on p.PID=mc.PID
where m.title="Anand"
order by p.name
I have tried several different queries and cannot seem to find one that works without causing an error
Incorrect syntax near keyword ' '
I have one table called Scores that saves the userID, week number, and that weeks score from a quiz.
Schema:
Scores (Id, userName, weekNumber, currentScore)
There are 12 weeks total, so in the end each user will have 12 entries in this table
I have another table Leaderboard that has schema :
Leaderboard (Id, userName, week1, week2, week3 ..... week12, totalScore)
Each user will only have one entry in this table.
I have been trying to save the sum of the currentScore from Scores into the totalScore attribute of Leaderboard and cannot seem to figure out the correct syntax.
My query is as follows:
UPDATE t1
SET t1.totalScore = t2.completeScore
FROM dbo.Leaderboard AS t1,
((SELECT Id, SUM(weeklyScore) AS completeScore FROM dbo.Scores) as F
INNER JOIN
(SELECT Id FROM dbo.Scores GROUP BY Id) AS S ON F.Id = S.Id) AS t2
WHERE t1.Id = t2.Id
Try this and let us know how it goes:
var total1 = ("UPDATE t1 " +
"SET t1.totalScore = t2.completeScore " +
"FROM dbo.Leaderboard AS t1, (SELECT F.Id, F.completeScore FROM " +
"(SELECT Id, SUM(weeklyScore) AS completeScore FROM dbo.Scores GROUP BY ID) as F " +
"INNER JOIN (SELECT Id FROM dbo.Scores/* GROUP BY Id*/) AS S "+
"ON F.Id = S.Id) AS t2 "+
"WHERE t1.Id = t2.Id");
By the way I think you were missing a GROUP BY clause in the definition of the F derived table and that you don't need the GROUP BY in the definition of the S derived table.
I'm using linq to sql on my asp.net project and i locked in somewhere. I select data amoung relationship tables and I use following codes. But the question is if supplierID is different than 0 there is no problem for query. Query is working as successful. But if supplierId is 0 query returns nothing. I want to use if statement when i join tables but how ?
My Codes,
EnvanterDataContext dc = new EnvanterDataContext();
var invent = from equipment in dc.tEquipments
where equipment.EquipmentID == id
orderby equipment.EquipmentID descending
join supplier in dc.tSuppliers on equipment.SupplierID equals supplier.SupplierID
join model in dc.tModels on equipment.ModelID equals model.ModelID
join equipmentType in dc.tEquipmentTypes on equipment.TypeID equals equipmentType.EquipmentTypeID
join equipmentStatus in dc.tEquipmentStatus on equipment.StatusID equals equipmentStatus.EquipmentStatusID
select equipment;
I want to use
EnvanterDataContext dc = new EnvanterDataContext();
var invent = from equipment in dc.tEquipments
where equipment.EquipmentID == id
orderby equipment.EquipmentID descending
if(equipment.SupplierID != 0)
join supplier in dc.tSuppliers on equipment.SupplierID equals supplier.SupplierID
join model in dc.tModels on equipment.ModelID equals model.ModelID
join equipmentType in dc.tEquipmentTypes on equipment.TypeID equals equipmentType.EquipmentTypeID
join equipmentStatus in dc.tEquipmentStatus on equipment.StatusID equals equipmentStatus.EquipmentStatusID
select equipment;
Thanks inadvance.
I've looked all around and spent way to long trying to convert this SQL statement into a Linq statement in VB. I'm sure it would be a good example for others out there - the statement is trying to pull products that have a many-to-many relationship with product categories, and the categories have a hierarchy of parents/children.
Here is the query I am trying to convert:
SELECT P.ProductID, P.ProductName, P.ProductSlug, P.PartNumber
FROM Products AS P
INNER JOIN Products_Categories AS PC ON PC.ProductID = P.ProductID
INNER JOIN Categories AS C ON PC.CategoryID = C.CategoryID
LEFT OUTER JOIN Categories AS P_Cats ON P_Cats.CategoryID = C.Parent
WHERE (C.CategoryID = 9) OR (C.Parent = 9) OR (P_Cats.Parent = 9)
I can get up to the point where I am trying to say "WHERE ... (P_Cats.Parent = 9)" but can't figure that part out.
THANKS!
Figured it out right after posting the question, but here is the answer in case anyone else finds it helpful:
Dim query = (From products In db.Products _
Join PC In db.Products_Categories On PC.ProductID Equals products.ProductID _
Join C In db.Categories On PC.CategoryID Equals C.CategoryID _
Group Join cat In db.Categories On cat.CategoryID Equals C.Parent Into C_Parents = Group _
From cParents In C_Parents.DefaultIfEmpty() _
Where (C.CategoryID = categoryID Or C.Parent = categoryID Or cParents.CategoryID = categoryID) _
And products.IsDeleted = False)
It was the line "From cParents In C_Parents.DefaultIfEmpty()" that I was leaving out.