View and Combine 2 rows in 1 from same table - c#

I have a problem to view my data as I want,
IDFlight | Dep1 | Des1| Date | IDFlight2 | Dep2 | Des2 | Date | Price
---------+------+-----+-------+-----------+------+------+--------+--------
2 | AYT | PRN |20.3.15| 3 | PRN | AYT | 27.3.15| 150
2 | AYT | PRN |20.3.15| 4 | PRN | AYT | 30.3.15| 150
1 | AYT | PRN |23.3.15| 4 | PRN | AYT | 30.3.15| 150
1 | AYT | PRN |17.3.15| 3 | PRN | AYT | 27.3.15| 150
So search query was with Dates +- 3 days both for 2 flights.
in my case every flight is registered alone in table Flights, each flight has his flight number and his direction, date and pricing(e.g return and one way).
now the problem here is, when user selects the return option, there will be displayed 2 flights in one row, (flight 1 go to destination, flight 2 return from destination) also there is a differences between dates line in the example in the picture.
what I am trying to achieve is displaying data like in example above , that every "one way " record should match with the " return " record. even if the first data is repeated.
I have done a lot of research but no result,
also I tried to do with a view but no success
I tried union no success.
#prmDepDay int, #prmDesDay int, #prmDateDep datetime, #prmFrom int, #prmTo int,
#prmDateRe datetime, #prmFromRe int, #prmToRe int, #prmTotalRe int
AS
BEGIN
DROP TABLE departureflights
SELECT TOP(100) PERCENT
t_flights.idflight,
t_flights.flightnumber,
t_departureairport.depairportname,
t_destinationairport.desairportname,
t_flights.startdate,
t_flights.totalseats
INTO departureflights
FROM t_flights
INNER JOIN t_departureairport
ON t_flights.iddepartureairport = t_departureairport.iddepartureairport
INNER JOIN t_destinationairport
ON t_flights.iddestinationairport = t_destinationairport.iddestinationairport
INNER JOIN t_flightdirections
ON t_flights.iddirection = t_flightdirections.iddirection
WHERE t_departureairport.iddepartureairport = #prmFrom
AND t_destinationairport.iddestinationairport = #prmTo
AND startdate >= Dateadd(day,-#prmDepDay,#prmDateDep)
AND startdate <= Dateadd(day,#prmDepDay,#prmDateDep)
--and TotalSeats>= #prmTotal
ORDER BY t_flights.startdate
DROP TABLE returnflights
SELECT t_flights.idflight,
t_flights.flightnumber AS ReFlightNumber,
t_departureairport.depairportname AS ReDepAirportName,
t_destinationairport.desairportname AS ReDesAirportName,
t_flights.enddate ,
t_flights.totalseats
INTO returnflights
FROM t_flights
INNER JOIN t_departureairport
ON t_flights.iddepartureairport = t_departureairport.iddepartureairport
INNER JOIN t_destinationairport
ON t_flights.iddestinationairport = t_destinationairport.iddestinationairport
INNER JOIN t_flightdirections
ON t_flights.iddirection = t_flightdirections.iddirection
WHERE t_departureairport.iddepartureairport = #prmFromRe
AND t_destinationairport.iddestinationairport = #prmToRe
AND enddate >= Dateadd(day,-#prmDesDay,#prmDateRe)
AND enddate <= Dateadd(day,#prmDesDay,#prmDateRe)
AND totalseats>= #prmTotalRe
ORDER BY t_flights.enddate

If you join the t_flights table with itself you should get both the outgoing and returning flight info in one row.
SELECT journey_out.idflight IDFlight,
journey_out.iddepartureairport Dep1,
journey_out.iddestinationairport Des1,
journey_out.enddate Date1,
journey_return.idflight IDFlight2,
journey_return.iddepartureairport Dep2,
journey_return.iddestinationairport Dep2,
journey_return.enddate Date2
FROM t_flights journey_out
INNER JOIN t_flights journey_return
ON journey_out.iddestinationairport = journey_return.iddepartureairport
AND journey_out.enddate < journey_return.startdate
ORDER BY journey_out.startdate
The first join condition makes sure that the flight is going home from the correct airport, and the second condition makes sure that the return journey does not start before the arrival.
If you want to see the one way options in the same result set as the return options you can change it to a LEFT JOIN instead of an INNER JOIN.

Related

is there a way to use OFFSET and FETCH in MS access or anything similiar in a query, set query has to be used in ASP.NET [duplicate]

Is it possible to emulate the following MySQL query:
SELECT * FROM `tbl` ORDER BY `date` DESC LIMIT X, 10
(X is a parameter)
in MS Access?
While the Access/JET TOP keyword does not directly provide an OFFSET capability, we can use a clever combination of TOP, a subquery, and a "derived table" to obtain the same result.
Here is an example for getting the 10 rows starting from offset 20 in a Person table in ORDER BY Name and Id...
SELECT Person.*
FROM Person
WHERE Person.Id In
(
SELECT TOP 10 A.Id
FROM [
SELECT TOP 30 Person.Name, Person.Id
FROM Person
ORDER BY Person.Name, Person.Id
]. AS A
ORDER BY A.Name DESC, A.Id DESC
)
ORDER BY Person.Name, Person.Id;
Essentially, we query the top 30, reverse the order, query the top 10, and then select the rows from the table that match, sorting in forward order again. This should be fairly efficient, assuming the Id is the PRIMARY KEY, and there is an index on Name. It might be that a specific covering index on Name, Id (rather than one on just Name) would be needed for best performance, but I think that indexes implicitly cover the PRIMARY KEY.
Another way - Let say you want from 1000 to 1999 records in a table called table1 (of course if you have that many records) you can do something like this.
MSSQL
SELECT *
FROM table1 LIMIT 1000, 1999;
MS Access
SELECT TOP 1000 *
FROM table1
Where ID NOT IN (SELECT TOP 999 table1.ID FROM table1);
To break this down
SELECT TOP NumA *
FROM table1
Where ID NOT IN (SELECT TOP NumB table1.ID FROM table1);
UpperLimit = 1999
LowerLimit = 1000
NumA = UpperLimit - LowerLimit + 1
ex. 1000 = 1999 - 1000 + 1
NumB = LowerLimit -1
ex. 999 = 1000 - 1
A better query would be:
SELECT Users.*
FROM Users
WHERE Users.id In
(
SELECT TOP X A.id
FROM [
SELECT TOP Y Users.*
FROM Users
ORDER BY Users.reg_date DESC
]. AS A
ORDER BY A.reg_date ASC
)
ORDER BY Users.reg_date DESC
Where
if((totalrows - offset) < limit) then
X = (totalrows - offset)
else
X = limit
And:
Y = limit + offset
For example, if total_rows = 12, and we set the limit to 10 (show 10 users per page), and the offset is calculated as p * limit - (limit) where p is the number of the current page, hence in the first page (p = 1) we will get: X = 12 and Y = 10, on the second X = 2 and Y = 20. The list of users is ordered by registration date (descending).
Simple and fastest solution.
myTable {ID*, Field2, Filed3...}
Assume your SortOrder contain primary KEY only
SELECT TOP PageItemsCount tb01.*
FROM myTable AS tb01
LEFT JOIN (
SELECT TOP OffsetValue ID FROM myTable ORDER BY ID ASC
) AS tb02
ON tb01.ID = tb02.ID
WHERE ISNULL(tb02.ID)
ORDER BY tb01.ID ASC
SortOrder based on other fields with duplicated values, in this case you must include your primary key in SortOrder as last one.
For exemple, myTable
+-------+--------+--------+
| ID | Field2 | Filed3 |
+-------+--------+--------+
| 1 | a1 | b |
| 2 | a | b2 |
| 3 | a1 | b2 |
| 4 | a1 | b |
+-------+--------+--------+
SELECT TOP 2 * From myTable ORDER BY FIELD2;
+-------+--------+--------+
| ID | Field2 | Filed3 |
+-------+--------+--------+
| 2 | a | b2 |
| 4 | a1 | b |
| 3 | a1 | b2 |
| 1 | a1 | b |
+-------+--------+--------+
SELECT TOP 2 * From myTable ORDER BY FIELD2, FIELD3;
+-------+--------+--------+
| ID | Field2 | Filed3 |
+-------+--------+--------+
| 2 | a | b2 |
| 4 | a1 | b |
| 1 | a1 | b |
+-------+--------+--------+
But if we add ID to sort order [AS LAST IN FIELDS LIST]
SELECT TOP 2 * From myTable ORDER BY FIELD2, ID;
+-------+--------+--------+
| ID | Field2 | Filed3 |
+-------+--------+--------+
| 2 | a | b2 |
| 1 | a1 | b |
+-------+--------+--------+
Final request
SELECT TOP PageItemsCount tb01.*
FROM myTable AS tb01
LEFT JOIN (
SELECT TOP OffsetValue ID FROM myTable ORDER BY Field2 ASC, ID
) AS tb02
ON tb01.ID = tb02.ID
WHERE ISNULL(tb02.ID)
ORDER BY tb01.Field2 ASC, tb01.ID
You can definitely get the the equivalent of "Limit" using the top keyword. See:
Access Database LIMIT keyword
No, JET SQL does not have a direct equivalent. As a workaround, you could add a WHERE clause that selects an ordered/id column between two values.
If possible, you can also use pass-through queries to an existing MySQL/other database.
While TOP in MS-Access can limit records returned, it does not take two parameters as with the MySQL LIMIT keyword (See this question).

C# DataSet Designer - AccesDB - Combine two rows into one

I need your help with an SQL query, that I am trying to build in C# Dataset Query Builder...
SELECT HouseHold.HHID, Client.FIRST_NAME, Client.LAST_NAME
FROM ((Client
INNER JOIN HouseHold_Client ON Client.CID = HouseHold_Client.CID)
INNER JOIN HouseHold ON HouseHold_Client.HHID = HouseHold.HHID)
Above code gives me the list of all HouseHolds (their ID) with Clients belonging to them:
HHID | FIRST_NAME | LAST_NAME
------------------------------
1 | Penelope | Grant
1 | Brian | Dyer
2 | James | Newman
2 | Richard | Parsons
.. but I can't figure out how to get people belonging to same HouseHold to show up on the same line, like this for a Data Grid View later on:
HHID | I_FIRST_NAME | I_LAST_NAME | II_FIRST_NAME | II_LAST_NAME
-----------------------------------------------------------------
1 | Penelope | Grant | Brian | Dyer
2 | James | Newman | Richard | Parsons
I have found loads of very similar questions, but very few had the same exact problem to solve. The ones (one or two) that really had the same problem and it had a solution, I just couldn't twist around my problem.
Any help is very much appreciated...
Thank you very much,
AD
Since you have only 2 persons per household, you can use the trick to get the minimum and maximum client Id per household. This is done in a subquery.
SELECT
X.HHID,
C1.FIRST_NAME AS I_FIRST_NAME, C1.LAST_NAME AS I_LAST_NAME,
C2.FIRST_NAME AS II_FIRST_NAME, C2.LAST_NAME AS II_LAST_NAME
FROM
(( SELECT
HHID, Min(CID) AS MinCId, IIf(Max(CID)=Min(CID), Null, Max(CID)) AS MaxCId
FROM HouseHold_Client
GROUP BY HHID
) X
INNER JOIN Client AS C1
ON X.MinCId = C1.CID)
LEFT JOIN Client AS C2
ON X.MaxCId = C2.CID;
The purpose of the IIf() expression is to output the maximum client Id only if it is different from the minimum client Id. To also return a record when MaxCId is Null, a LEFT JOIN is required on C2.
I did not join the HouseHold table here, since we only need the HHID from it, which is also available in HouseHold_Client. You can of course join it as well, if you need other columns from it.
Subquery:
( SELECT
HHID, Min(CID) AS MinCId, IIf(Max(CID)=Min(CID), Null, Max(CID)) AS MaxCId
FROM HouseHold_Client
GROUP BY HHID
) X
Subqueries must be enclosed in parentheses and be given a name (here X). X acts as a normal table having the columns HHID, MinCId and MaxCId in the main query. It is grouped by HHID. I.e., it returns one row per HHID. Min(CID) returns the smallest CID and Max(CID) largest CID per HHID.
In the case where you have 2 clients per HHID, this means that Min and Max will yield these 2 clients. If you have only 1 client, then both Min and Max will return the same client. If this is the case, then the IIf will return Null instead of Max(CID) to avoid returning twice the same client.

Order a 3 level object

I have this scheme
Document
DocumentId
Position
PositionId
DocumentId
Coordonate
CoordonateId
PositionId
Km
Road
RoadId
CoordonateId
Name
I need to order the documents by Road.Name and then by lowest Coordonate.Km. I tried to order them in SQL and EF but with no luck so now I use this code that is very slow:
foreach (var document in documents)
foreach (var position in documentPositions)
{
if (!position.Coordonates.Any())
continue;
var minKm =
position.Coordonates.OrderBy(a => a.Km).FirstOrDefault().Km.Value;
dictionary.Add(document, minKm);
break;
}
var sorted= dictionary.OrderBy(a => a.Key.RoadName).ThenBy(a => a.Value);
document.RoadName is a property that concatenates all the Road.Names that may be in the document.
LE:
I made a sqlfiddle at http://sqlfiddle.com/#!18/90b00/2/0 Hope that helps
You can write a subquery by Coordonates table, using rank function with windows function to get the samllest km, then do join
select Documents.DocumentId,
Documents.Name,
Roads.Name,
MIN(km) km
from Documents
INNER JOIN Positions ON Documents.DocumentId=Positions.DocumentId
INNER JOIN (
select
PositionId,
CoordonateId,
km,
rank() over(partition by PositionId order by Km) rn
from Coordonates
) Coordonates ON Positions.PositionId=Coordonates.PositionId and rn =1
INNER JOIN Roads ON Coordonates.CoordonateId=Roads.CoordonateId
group by Documents.DocumentId,
Documents.Name,
Roads.Name
Order By Roads.Name,km
[Results]:
| DocumentId | Name | Name | km |
|------------|------|------|----|
| 2 | Doc2 | A1 | 10 |
| 1 | Doc1 | A2 | 10 |
| 3 | Doc3 | A2 | 15 |
sqlfiddle
You can find min value without using OrderBy and then FirstOrDefault Instead use Min which should be a little bit faster.
var minKm = position.Coordinates.Min(coord => coord.Km.Value);
Update: maybe your code is slow because position.Coordinates is not loaded from the database and your code does extra database roundtrip for every document which is why it is slow. Please ensure all data is already loaded and the foreach loop is actually causing that slowness. If coordinates data aren't included you can add Include(...) statement into your EF query.

how to get only those which have maximum value in a specified column in asp.net c#

I have a table with "customer_id, date, installment_no, amount" columns. I want to get the information of last installment of each customer_id till today. here installment_no is int type and when a new installment is deposited, the installment_no is increased by 1 in new entry. My table look like:
CS1001 | 12-06-2013 | 1 | 2500
CS1002 | 19-06-2013 | 1 | 1600
CS1001 | 14-07-2013 | 2 | 2500
I want to get a sqlcommand statement for do so.
Group all records by customer_id, then order all customer's records by installment_no, and select only record with max installment_no from each group:
from c in customers
group c by c.customer_id into g
select g.OrderByDescending(x => x.installment_no).First()
Same with pure SQL if you don't use Linq
SELECT c.* FROM Customers c
INNER JOIN (
SELECT customer_id, MAX(installment_no) max_installment
FROM Customers
GROUP BY customer_id
) cmax
ON c.customer_id = cmax.customer_id
AND c.installment_no = cmax.max_installment
var result = list.GroupBy(x=>x.customer_id)
.Select(g=>g.OrderByDescending(y=>y.installment_no).First())
.ToList();

Sql query with complex joins

I am developing c# application.
I am using OLEDB connections.
I have following two tables>>
payment
AdmissionNumber | StudName |
1 John
2 Smith
paymentDetails
AdmissionNumber | RemainingFee | Date | Payment
1 5000 10/10/2012 3000
1 3000 10/11/2012 2000
2 4000 15/11/2012 3000
1 1000 10/12/2012 2000
In this I want to get the table result as following>>
AdmissionNumber | Name | Date |RemainingPayment|Payment|
1 John 10/12/2012 1000 2000
In this case Admission number and date is already provided in the form via textbox and datetimepicker.
In this case Admission number and date is already provided in the form
via textbox and datetimepicker.
So you want to search for a specific Admission number and a date. If so, then try this:
SELECT
p.AdmissionNumber,
p.Name,
pd.Date,
pd.RemaingFee AS RemainingPayment,
pd.Payment
FROM Payment p
INNER JOIN PaymentDetails pd ON p.AdmissionNumber = pd.AdmissionNumber
WHERE p.AdmissionNumber = #AdmissionNumberParamFromTxtBox
AND pd.Date = #DateParamFromTheotherTextBox;
This will give you the exact result. Matching between master and the last record of the details. You should have an Primary key column in the details.
Select *
From Payment
Left Outer Join
PaymentDetail
On PaymentDetail.Id = (
Select Top 1
A.Id
From PaymentDetail As A
Where A.AdmissionNumber = Payment.AdmissionNumber
Order By A.Date Desc
)
Cheers
SELECT
p.AdmissionNumber,
p.Name,
MAX(pd.Date) AS Date,
pd.RemaingFee AS RemainingPayment,
pd.Payment
FROM Payment p
INNER JOIN PaymentDetails pd ON p.AdmissionNumber = pd.AdmissionNumber
GROUP BY p.AdmissionNumber,pd.Payment,p.Name,pd.RemaingFee

Categories

Resources