ASP.NET MVC 5 Join on Between, no primary key - asp.net

I have some interesting code to look at.
I have three tables:
Table A has 4 columns:
TablePK
UserID
TableBFKID
Score
Table B has 3 columns:
TablePK
Name
ShortName
Table c has 4 columns:
TablePK
ScoreMin
ScoreMax
Modifier
So when the full join happens it looks like this:
SELECT B.ShortName
, A.Score
, C.Modifier
FROM TableA A
INNER JOIN TableB B ON a.TablePK= B.TablePK
INNER JOIN TableC C ON A.Score BETWEEN C.ScoreMin AND C.ScoreMax
The results would look like this:
ShortName, Score, Modifier. EX:
CHA, 19, 4
Now I know how to do an Entity Framework join if there is an actual PK or FK, or even if there is only a 0:1 relationship.
But how do you do the join when there is neither a PK nor an FK?

LINQ, including LINQ to Entities, only supports equi-joins.
But you can run SQL directly:
var res = myContext.Database.SqlQuery<TResult>("SQL goes here", parmeters...);
and EF will map the columns of the result set to the properties of TResult (which needs to other connection to the context: it does not need to be an entity type with a DbSet typed property in the context).

In this case I wouldn't try to join them, just use a sub-select in your linq to select from the un-joined table where the scores are between your wanted ranges.
var results = context.TableA
.Select(a => new {
score = a.Score, //add all needed columns
tableCs = context.TableC.Where(c => a.Score >= c.ScoreMin && a.Score <= c.ScoreMax)
});

Related

Getting a min(date) AND max(date) AND their respective titles

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.

Sql Join between two tables using Entity framework - Trying to bind Gridview data from two tables

I have a gridview and originally I was binding data from one table (Table 1) and it was straightforward
gvUsers.dataSource = class.getUsers()
gvUsers.databind()
Function getUsers () As List (Of Users)
Return (From X in Table1 Select x).ToList()
End Function
However, some of my data are pointing to another table and there is no relationship between tables ( no foreign key)
Table 1
UID Name Age Blood Type Test Type
1 Sam 22 2 3
2 Jane 23 2 4
Table 2
ID Domain Code Description
1 Blood Type A A
2 Blood Type B B
3 Test Type 1 1
4 Test Type 2 2
Currently In the gridView I see Blood Type as values 2 and Test type 3, 4 ( The second table ID) but I should get the Code column values in Table 2.
How can I join those two tables - I know if there is foreign key but the fact a column name is equivelant to row data name makes it hard for me to figure out!
Cheers
Try Code
var result = (from p in Table1.AsEnumerable()
join Blood in Table2.AsEnumerable() on p.BloodType equals Blood .ID
join Test in Table2.AsEnumerable() on p.TestTyoe equals Test .ID
select new With
{
uid = p.UID,
Name = p.name,
Age = p.age,
BloodType = Blood.Code,
TestType = Test .Code
}).ToList();
Sql Query IS :
select UID ,Name,Age,B.Code as BloodType ,T.Code as TestType From Table1
inner join Table2 B on Table1.BloodType = B.ID
inner join Table2 T on Table1.TestType= T.ID
The Used Vb then
Dim result = from p in Table1.AsEnumerable()
join Blood in Table2.AsEnumerable() on p.BloodType equals Blood .ID
join Test in Table2.AsEnumerable() on p.TestTyoe equals Test .ID
select
p.UID,
p.name,
p.age,
Blood.Code,
Test.Code
gvUsers.DataSource = result
Try this one:
select table1.*, table2.* from table1
inner join table2 on table1.Blood Type = table2.id
You can select you desired columns from both tables.

Zipping rows with the same "key" while joining tables

I have two tables, one with objects, one with properties of the objects. Both tables have a personal ID and a date as "key", but since multiple orders of objects can be done by one person on a single day, it doesn't match well. I do know however, that the entries are entered in the same order in both tables, so it is possible to join on the order, if the personID and date are the same.
This is what I want to accomplish:
Table 1:
PersonID Date Object
1 20-08-2013 A
2 13-11-2013 B
2 13-11-2013 C
2 13-11-2013 D
3 21-11-2013 E
Table 2:
PersonID Date Property
4 05-05-2013 $
1 20-08-2013 ^
2 13-11-2013 /
2 13-11-2013 *
2 13-11-2013 +
3 21-11-2013 &
Result:
PersonID Date Object Property
4 05-05-2013 $
1 20-08-2013 A ^
2 13-11-2013 B /
2 13-11-2013 C *
2 13-11-2013 D +
3 21-11-2013 E &
So what I want to do, is join the two tables and "zip" the group of entries that have the same (PersonID,Date) "key".
Something called "Slick" seems to have this (see here), but I'd like to do it in SQLite.
Any advice would be amazing!
You are on the right track. Why not just do a LEFT JOIN between the tables like
select t2.PersonID,
t2.Date,
t1.Object,
t2.Property
from table2 t2
left join table1 t1 on t2.PersonID = t1.PersonID
order by t2.PersonID
Use a additional column to make every key unique in both tables. For example in SQLite you could use RowIDs to keep track of the order of insertion. To store this additional column in the database itself might be useful for other queries as well, but you do not have to store this.
First add the column ID to both tables, the DDL queries should now look like this: (make sure you do not add the primary key constraint until both tables are filled.
CREATE TABLE table1 (
ID,
PersonID,
Date,
Object
);
CREATE TABLE table2 (
ID,
PersonID,
Date,
Property
);
Now populate the ID column. You can adjust the ID to your liking. Make sure you do this for table2 as well:
UPDATE table1
SET ID =(
SELECT table1.PersonID || '-' || table1.Date || '-' || count( * )
FROM table1 tB
WHERE table1.RowID >= tB.RowID
AND
table1.PersonID == tB.PersonID
AND
table1.Date == tB.Date
);
Now you can join them:
SELECT t2.PersonID,
t2.Date,
t1.Object,
t2.Property
FROM table2 t2
LEFT JOIN table1 t1
ON t2.ID = t1.ID;

Querying Two data tables asp.net

I have 2 tables each with same fields basically containing
table1.ItemCode table1.Qty
table2.ItemCode table2.Qty
i am querying these two tables from sql by the following command
SELECT c.Code ,
t1.Code ,
t1.Qty ,
t2.Code ,
t2.Qty
FROM ( SELECT Code
FROM dbo.Table1
UNION
SELECT Code
FROM dbo.Table2
) c
LEFT OUTER JOIN dbo.Table1 t1 ON c.Code = t1.Code
LEFT OUTER JOIN dbo.Table2 t2 ON c.Code = t2.Code
WHERE t1.Code IS NULL
OR t2.Code IS NULL
OR t1.Qty <> t2.Qty
this query provides me with the item codes that exist in both tables
that have only different quantities
for example if item: x has qty 2 and in the second table Item x has qty 4
this item would show as: x 2 4
however if Item x has qty 2 and in the second table also the same qty
this item will not appear in the result
the problem is that in my situation these 2 tables are two data Tables in my asp.net
project
i need to execute the same query but on these two data tables
how can that be done or is their any other possible solution to get my result from these 2
data tables
This is quite straightforward.
DataTable table1;
DataTable table2;
//Initialize your DataTables here
var result = (from row1 in table1.AsEnumerable()
join row2 in dataTable2.AsEnumerable() on row1["Code"] equals row2["Code"]
where !object.Equals(row1["Qty"], row2["Qty"])
select new { Code = row1["Code"], table1Qty = row1["Qty"], table2Qty = row2["Qty"] })
.ToArray();
Rows from the two tables are joined on Code.
join row2 in dataTable2.AsEnumerable() on row1["Code"]
Subsequently, rows with the same Qty values are filtered
where !object.Equals(row1["Qty"], row2["Qty"])

Querying on count value having ()

I'm having difficulty with a query which displays records according to their fill rate.
For instance, a vacancy can have no bookings or some bookings. If a vacancy has bookings, they can be in the form of 'active [1]', 'pending [0]'. The query I have written so far works if the vacancy has booking records but I can't get it to work if it doesn't have booking records.
My query (which works) for vacancies with a booking is as follows:-
SELECT v.*, j.job_category_name, bu.business_unit_name
FROM vacancy v
INNER JOIN job_category j ON j.job_category_id = v.job_category_id
INNER JOIN business_unit bu ON bu.business_unit_id = v.business_unit_id
INNER JOIN booking b ON b.vacancy_id = v.vacancy_id
INNER JOIN booking_status bs ON bs.id = b.booking_status_id
WHERE
v.vacancy_status <> 'revoked' AND
v.vacancy_reference <> 'auto-generated booking' AND
v.business_unit_id IN (series of primary keys) AND
(bs.booking_status_type_id = 1 OR bs.booking_status_type_id = 2)
GROUP BY v.vacancy_id
HAVING v.vacancy_limit > count(b.booking_id)
ORDER BY v.vacancy_id DESC
I thought by changing the join of b and bs to LEFT JOIN would have worked, but it hasn't.
Any ideas?
Without a copy of your schema to work from, it's difficult to tell exactly, but when you changed booking and bookingstatus to LEFT JOINs, did you also modify your WHERE clause so that it read something like:
WHERE
v.vacancy_status <> 'revoked' AND
v.vacancy_reference <> 'auto-generated booking' AND
v.business_unit_id IN (series of primary keys) AND
(ISNULL(bs.booking_status_type_id, 1) = 1 OR ISNULL(bs.booking_status_type_id, 2) = 2)
i.e. Ensured that the full WHERE clause would be satisfied, thus not stripping out the records where all the values for columns from booking and bookingstatus were NULL?
Try LEFT OUTER JOIN for the tables for which the joins may return 0 matches.
For eg:- in your case have LEFT OUTER JOIN for b and bs and check

Resources