Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Distinct data from Join query

Basically I have 2 tables. Lets say A and B.

A has columns like id(PK), pin, name, address

id(PK)  pin             name    address
1        aaa-111-aaa    AAA ------
2        bbb-222-bbb    BBB ------
3        ccc-333-ccc    CCC --------

B has columns like appName, apprequestTime, appAccectTime, id(FK).

appName apprequestTime  appAccectTime    id(FK).
LLL          2012-4-01  2012-4-01    1
NNN          2012-4-08  2012-5-01    2
QQQ          2012-4-05  2012-4-01    1
MMM          2012-4-02  2012-4-02    2
PPP          2012-5-01  2012-5-01    1

There can be multiple id rows in the B table as it is Foreign Key.

Now, the problem is I am trying to get all the records of one pin of a certain apprequestTime.

I am trying inner join but it shows the pin because of the id in table B.

pin         apprequestTime
aaa-111-aaa     2012-4-01
aaa-111-aaa     2012-4-05
bbb-222-bbb     2012-4-08
bbb-222-bbb     2012-4-02

but the result I am expecting should be:

pin            apprequestTime
aaa-111-aaa    2012-4-01
               2012-4-05
bbb-222-bbb    2012-4-08
               2012-4-02

Can any one help:)

like image 635
Aqua Avatar asked Mar 07 '26 16:03

Aqua


1 Answers

In SQL Server 2005+ you can use row_number() for this type of request:

;with cte as
(
  select a.pin, b.apprequestTime,
    row_number() over(partition by a.pin 
                      order by b.apprequestTime) rn
  from tablea a
  inner join tableb b
    on a.id = b.id
) 
select case when rn = 1 then pin else '' end pin, 
  apprequestTime
from cte;

See SQL Fiddle with Demo

Or without CTE:

select case when rn = 1 then pin else '' end pin, 
  apprequestTime
from 
(
  select a.pin, b.apprequestTime,
    row_number() over(partition by a.pin 
                      order by b.apprequestTime) rn
  from tablea a
  inner join tableb b
    on a.id = b.id
) t1

See SQL Fiddle with Demo

like image 176
Taryn Avatar answered Mar 10 '26 06:03

Taryn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!