Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self join issue

I have a table called tblAccInfo, below is the table data. I need output like below.

Input
PolicyNumber    BankAc   StorageDate    VerNum
6003210400      123      2012-01-01     1
6003210400      164      2012-01-03     2
6003210400      860      2012-01-05     3
6004317654      301      2012-02-05     1
6004317654      615      2012-03-01     2
6004317654      253      2012-03-12     3
6004317654      887      2012-04-03     4

OUTPUT

PolicyNumber  IntialBankAc IntialSDate VerNum  LatestBankAc LatestSDate VerNum
6003210400    123          2012-01-01  1       860          2012-01-05  3
6004317654    301          2012-02-05  1       887          2012-04-03  4

I have tried with below self join, but did not succeeded. Please help me out in this.

Select DISTINCT
    P.PolicyNumber,
    P.BankAc [IntialBankAc],
    P.StorageDate IntialSDate],
    P.VerNum,
    P1.BankAc [LatestBankAc],
    P1.StorageDate [LatestSDate],
    P1.VerNum
FROM tblAccInfo P
INNER JOIN tblAccInfo P1
ON P1.PolicyNumber=P.PolicyNumber
AND (P.BankAc<>P1.BankAc AND P.StorageDate<>P1.StorageDate AND P.VerNum<>P1.VerNum)
like image 690
Simhadri Avatar asked Jun 06 '12 21:06

Simhadri


People also ask

What is self join with example?

A self join is a join in which a table is joined with itself (which is also called Unary relationships), especially when the table has a FOREIGN KEY which references its own PRIMARY KEY. To join a table itself means that each row of the table is combined with itself and with every other row of the table.

What is a self join?

A self join is a regular join, but the table is joined with itself.

What is the point of a self join?

A self join allows you to join a table to itself. It helps query hierarchical data or compare rows within the same table. A self join uses the inner join or left join clause.

Is self join important?

One thing to notice is that when you are self joining it is necessary to use an alias for the table otherwise the table name would be ambiguous. It is useful when you want to correlate pairs of rows from the same table, for example a parent - child relationship.


1 Answers

Try this:

SELECT
    T1.PolicyNumber,
    T2.BankAc AS IntialBankAc,
    T2.StorageDate AS IntialSDate,
    T2.VerNum AS InitalVerNum,
    T3.BankAc AS LatestBankAc,
    T3.StorageDate AS LatestSDate,
    T3.Vernum AS LatestVerNum
FROM
(
    SELECT
        PolicyNumber,
        MIN(VerNum) AS MinVerNum,
        MAX(VerNum) AS MaxVerNum
    FROM tblAccInfo
    GROUP BY PolicyNumber
) AS T1
JOIN tblAccInfo AS T2
ON T1.PolicyNumber = T2.PolicyNumber
AND T1.MinVerNum = T2.VerNum
JOIN tblAccInfo AS T3
ON T1.PolicyNumber = T3.PolicyNumber
AND T1.MaxVerNum = T3.VerNum

See it working online: sqlfiddle

like image 113
Mark Byers Avatar answered Oct 06 '22 03:10

Mark Byers