SQL statement converting to LINQ? - c#

Okay...... SO I have a drop down list that work but i wont to spice it up adding more checks.... in the asp format i have managed to check date restriction but i need to count from another table results but in ASP not sure how to count.... Hes the ASP Version I made that works i've done an SQL On to Get an idea
Here is the LINQ version only thing don't work is the get number of tickets already assigned to timetable
var query = from table in db.Timetables
join tick in db.Tickets on table.ID equals tick.TimetableID
where table.Schedual_Date > DateTime.Today
&& table.Advance_Tickets > "NEEDS TO GET NUMBER OF TICKETS ASSIGNED TO TIMETABLE"
select table;
SQL VERSION
SELECT
COUNT(Tickets.TimetableID) AS NoTickets, * FROM Tickets
JOIN Timetable ON Tickets.TimetableID=Timetable.ID
Where timetable.Schedual_Date > (TODAYS DATE)
&& Timetable.Advance_Tickets > NoTickets

If you are looking LINQ equivalent for SQL query as below
SELECT * FROM
Timetable Timetable
Where timetable.Schedual_Date > getDate()
AND Timetable.Advance_Tickets >= (SELECT COUNT(1) FROM Tickets Tickets WHERE Tickets.TimetableID=Timetable.ID)
you can try
var query = from table in timeTables
where table.SchedualDate > DateTime.Today
&& table.AdvanceTickets > (tickets.Count(a => a.TimeTableId == table.Id))
select table;

Use .Count() function to get the count. In your case tick.Count() would help. for example,
var query = from table in db.Timetables
join tick in db.Tickets on table.ID equals tick.TimetableID
where table.Schedual_Date > DateTime.Today
&& table.Advance_Tickets > tick.Count()
select table;

Related

Linq grouping multiple where condition

I have a query that I wrote in SQL, which works, and I am trying to move this to the appropriate LINQ statement, and can't seem to get it quite right.
The SQL query:
select sku
from Table
group by sku
having count(sku) > 1 and count(distinct(unit)) > 1
and what I have so far with LINQ
var dupCount = (from val in dt.AsEnumerable()
group val by new {sku = val[4]} into grp
where grp.Count() > 1 && grp.unit.Distinct().Count() > 1
select grp).ToList();
I cant seem to figure out how to tell the where within the group to only pull the records with a distinct "unitreserve".
I cant seem to figure out how to tell the where within the group to only pull the records with a distinct "unitreserve".
Select the "unitreverse" field, apply Distinct and then Count it:
where grp.Count() > 1 &&
grp.Select(dr => dr["unitreserve"]).Distinct().Count() > 1

Subquery in Linq query giving A query body must end with a select clause or a group clause

booked - below - should be the sum of the NumberBooked column from the Bookings table - which has a link to the TourDates table on the TourDateId.
However I'm getting the error A query body must end with a select clause or a group clause
Can anyone please help me fix this query?
Thank you,
Mark
var tours = from t in Tours
join d in TourDates on t.TourId equals d.TourId
where d.Date == dt
select new
{
t.TourId,
d.TourDateId,
booked = (from b in Bookings where d.TourDateId == b.TourDateId)
Select new {bk.Sum(b.NumberBooked()}
};
I believe this:
booked = (from b in Bookings where d.TourDateId == b.TourDateId) // oops
Select new {bk.Sum(b.NumberBooked()}
should be this:
booked = (from b in Bookings where d.TourDateId == b.TourDateId // move from here
select new {bk.Sum(b.NumberBooked()}) // to here
Note that I moved the end parenthesis ) so that it comes after the select, not after TourDateId
The closing round paranthesis ends the query which needs a select at the end.
Why don't you use method syntax? It is much better readable in this case. Also, a Select is optional with .Where and method syntax:
join d in TourDates on t.TourId equals d.TourId
where d.Date == dt
select new
{
t.TourId,
d.TourDateId,
booked = Bookings.Where(b => d.TourDateId == b.TourDateId)
.Sum(b => b.NumberBooked())
};
Note that i have removed the anonymous type since you just want the sum of that column
should be the sum of the NumberBooked column from the Bookings table -
which has a link to the TourDates table on the TourDateId.

How to filter LINQ query by table column and get count

I'm trying to get a list of students based on their status, grouped by their college.
So I have three tables, Students and Colleges. Each student record has a status, that can be 'Prospect', 'Accepted' or 'WebApp'. What I need to do is get a list of students based on the status selected and then display the College's name, along with the number of students that go to that college and have their status set to the status passed in. I think this needs to be an aggregate query, since the counts are coming from the string Status field.
I'm not sure how to do this in MS SQL, since the count is coming from the same table and it's based on the status field's value.
Here is the start of my query, which takes in the search parameters, but I can't figure out how to filter on the status to return the counts.
SELECT Colleges.Name, [Status], Count([Status])
FROM Students
JOIN Colleges ON Students.UniversityId = Colleges.id OR Students.+College = Colleges.Name
GROUP BY Students.[Status], Colleges.Name
ORDER BY Colleges.Name;
Accepts = Status('Accepted')
WebApps = Status('WebApp')
Total = Sum(Accpets + WebApps)
Select
Colleges.Name,
SUM(Case when Students.Status like 'Accepted' then 1 else 0 end) Accepts,
SUM(Case when Students.Status like 'WebApp' then 1 else 0 end) WebApps,
COUNT(*) Total
from Students
join Colleges on Students.UniversityId = Colleges.Id OR Students.CurrentCollege = Colleges.Name
Group by Colleges.Name
The LINQ:
var results =
(from c in db.Colleges // db is your DataContext
select new
{
CollegeName = c.Name,
AcceptedStatus = db.Students.Count(r => r.Status.ToUpper() == "ACCEPTED" && (r.UniversityId == c.Id || r.CurrentCollege == c.Name)),
WebAppStatus = db.Students.Count(r => r.Status.ToUpper() == "WEBAPP" && (r.UniversityId== c.Id || r.CurrentCollege == c.Name)),
Total = db.Students.Count(s => s.UniversityId == c.Id || s.CurrentCollege == c.Name)
}).ToList();
Try this http://www.linqpad.net/
Its free and you can convert the linq to sql queries

MySQL entity framework Group and Select By Date

I have a MySQL database with a table 'Clicks'. There's a 'Created' column (datetime) which I'd like to group by and select the year, month and day part. I want to count the records per day within a specific range of dates (startDate and endDate).
var query = from c in scope.Entities.Clicks
where c.Created >= startDate && c.Created <= endDate
group c by new {c.Created.Year, c.Created.Month, c.Created.Day}
into grouped
select new {
Year = grouped.Key.Year,
Month = grouped.Key.Month,
Day = grouped.Key.Day,
Clicks = grouped.Count()
};
This produces a bad query:
SELECT
`GroupBy1`.`K1` AS `C1`,
`GroupBy1`.`K2` AS `C2`,
`GroupBy1`.`K3` AS `C3`,
`GroupBy1`.`K4` AS `C4`,
`GroupBy1`.`A1` AS `C5`
FROM (SELECT
COUNT(1) AS `A1`
FROM `Click` AS `Extent1`
WHERE (`Extent1`.`Created` >= #p__linq__0) AND (`Extent1`.`Created` <= #p__linq__1)
GROUP BY
1,
YEAR(`Extent1`.`Created`),
MONTH(`Extent1`.`Created`),
DAY(`Extent1`.`Created`)) AS `GroupBy1`
With an error: MySql.Data.MySqlClient.MySqlException: Can't group on 'A1'
What do I do wrong? Or is this a MySql connector bug? I tried MySQL connectors 6.5.4 and 6.6.5
DJ KRAZE I tried your approach and it turns out that the double "select" is necessary to produce a correct query by EF. Thanks! I post the full answer here if anyone needs it.
I tested both ways and both work:
var subQuery = from c in scope.Entities.Clicks
where c.Created >= startDate && c.Created <= endDate
select new { c.Created.Year, c.Created.Month, c.Created.Day };
var query = from c in subQuery
group c by new {c.Year, c.Month, c.Day}
into grouped
select new {
Year = grouped.Key.Year,
Month = grouped.Key.Month,
Day = grouped.Key.Day,
Clicks = grouped.Count()
};
And
var query = scope.Entities.Clicks.Where(c => c.Created >= startDate && c.Created <= endDate)
.Select(c => new { c.Created.Year, c.Created.Month, c.Created.Day})
.GroupBy(c => new {c.Year, c.Month, c.Day})
.Select(grouped => new { Clicks = grouped.Count(), grouped.Key.Year, grouped.Key.Month, grouped.Key.Day});
These give the correct mysql query:
SELECT
1 AS `C1`,
`GroupBy1`.`K1` AS `C2`,
`GroupBy1`.`K2` AS `C3`,
`GroupBy1`.`K3` AS `C4`,
`GroupBy1`.`A1` AS `C5`
FROM (SELECT
`Project1`.`C1` AS `K1`,
`Project1`.`C2` AS `K2`,
`Project1`.`C3` AS `K3`,
COUNT(1) AS `A1`
FROM (SELECT
YEAR(`Extent1`.`Created`) AS `C1`,
MONTH(`Extent1`.`Created`) AS `C2`,
DAY(`Extent1`.`Created`) AS `C3`
FROM `Click` AS `Extent1`
WHERE (`Extent1`.`Created` >= #p__linq__0) AND (`Extent1`.`Created` <= #p__linq__1)) AS `Project1`
GROUP BY
`Project1`.`C1`,
`Project1`.`C2`,
`Project1`.`C3`) AS `GroupBy1`
(I still think this is a bug and my first query should work as well btw)

How can I convert this SQL Query into LINQ (OVER (PARTITION BY Date))

Here's the query I'm trying to convert into Linq:
SELECT R.Code,
R.FlightNumber,
S.[Date],
S.Station,
R.Liters,
SUM(R.Liters) OVER (PARTITION BY Year([Date]), Month([Date]), Day([Date])) AS Total_Liters
FROM S INNER JOIN
R ON S.ID = R.SID
WHERE (R.Code = 'AC')
AND FlightNumber = '124'
GROUP BY Station, Code, FlightNumber, [Date], Liter
ORDER BY R.FlightNumber, [Date]
Thanks for any help.
UPDATE: Here is the Linq code I'm trying it on; I cannot make the OVER PARTITION by Date.
var test =
(from record in ent.Records join ship in ent.Ship on record.ShipID equals ship.ID
orderby ship.Station
where ship.Date > model.StartView && ship.Date < model.EndView && ship.Station == model.Station && record.FlightNumber == model.FlightNumber
group record by new {ship.Station, record.Code, record.FlightNumber, ship.Date, record.AmountType1} into g
select new { g.Key.Station, g.Key.Code, g.Key.FlightNumber, g.Key.Date, AmmountType1Sum = g.Sum(record => record.AmountType1) });
Execute query first without aggregation:
var test =
(from record in ent.Records join ship in ent.Ship on record.ShipID equals ship.ID
orderby ship.Station
where ship.Date > model.StartView && ship.Date < model.EndView && ship.Station == model.Station && record.FlightNumber == model.FlightNumber
select new {ship.Station, record.Code, record.FlightNumber, ship.Date, record.AmountType1};
Then calculate sum
var result =
from row in test
select new {row.Station, row.Code, row.FlightNumber, row.Date, row.AmountType1,
AmountType1Sum = test.Where(r => r.Date == row.Date).Sum(r => r.AmountType1) };
This should produce the same effect as database query. Code above may contain errors, because I wrote it only here.
I've answered a similar thread on: LINQ to SQL and a running total on ordered results
On that thread it was like this:
var withRuningTotals = from i in itemList
select i.Date, i.Amount,
Runningtotal = itemList.Where( x=> x.Date == i.Date).
GroupBy(x=> x.Date).
Select(DateGroup=> DateGroup.Sum(x=> x.Amount)).Single();
In you situation, you might have to join the two tables together first while grouping, then run the same concept above on the joined table result.

Categories