Click here to Skip to main content
11,706,159 members (52,080 online)
Click here to Skip to main content

Tagged as

JOIN Instead of Repeating a Subquery

, 6 Feb 2011 CPOL 2.2K 2
Rate this:
Please Sign up or sign in to vote.
As an alternate, I would like to share the following query using the previous table definition using RANK:DECLARE @FirstTable table(FirstName varchar(20))DECLARE @SecondTable table (ID int, FirstName varchar(20), LastName varchar(20), FirstNameHashCode varchar(20), ...
As an alternate, I would like to share the following query using the previous table definition using RANK:

DECLARE @FirstTable table(FirstName varchar(20))
DECLARE @SecondTable table
    (ID int,
    FirstName varchar(20),
    LastName varchar(20),
    FirstNameHashCode varchar(20),
    FirstNameFrequency int)
INSERT INTO @FirstTable(FirstName) VALUES('Billy')
INSERT INTO @FirstTable(FirstName) VALUES('Super')
INSERT INTO @SecondTable(ID, FirstName, LastName, FirstNameHashCode, FirstNameFrequency)
    VALUES(1, 'Billy', 'Mays', '0XB$22', 22)
INSERT INTO @SecondTable(ID, FirstName, LastName, FirstNameHashCode, FirstNameFrequency)
    VALUES(2, 'Billy', 'TheKid', '0XB$22', 22)
INSERT INTO @SecondTable(ID, FirstName, LastName, FirstNameHashCode, FirstNameFrequency)
    VALUES(3, 'Super', 'Man', 'SJ3JD', 40)
INSERT INTO @SecondTable(ID, FirstName, LastName, FirstNameHashCode, FirstNameFrequency)
    VALUES(4, 'Super', 'Friends', 'SJ3JD', 40)
 
-------------- Here is the query
SELECT
    ST.FirstNameHashCode,
    ST.FirstNameFrequency,
    ST.ID
FROM @FirstTable AS FT
JOIN 
   (SELECT FirstName, ID, FirstNameHashCode, FirstNameFrequency,
           RANK() OVER(PARTITION BY FirstName ORDER BY ID) AS NRANK
   FROM @SecondTable
   ) AS ST ON FT.FirstName = ST.FirstName AND ST.NRANK = 1

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Goutam Patra
Technical Lead
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150819.1 | Last Updated 7 Feb 2011
Article Copyright 2011 by Goutam Patra
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid