Sunday, March 25, 2012

Distinct list

Let’s say we have two tables with the following values:
Table p1: Product Table p2: Product
-- --
A B
B C
C D
C D
Task #1 - In a single query, generate a unique list of values from both
tables (i.e. A, B, C, D).Hi Danlin,
Select Distinct Product From P1
Union
Select Distinct Product From P2
<Throw in an order by here if you want>
Order By
Product
That should do it.
Richard|||SELECT product
FROM P1
UNION
SELECT product
FROM P2
David Portas
SQL Server MVP
--|||Someone throw me this problem and he wants a single query solution not using
union. Sorry about the confusion. Thanks.
"danlin" wrote:

> Let’s say we have two tables with the following values:
>
> Table p1: Product Table p2: Product
> -- --
> A B
> B C
> C D
> C D
>
> Task #1 - In a single query, generate a unique list of values from both
> tables (i.e. A, B, C, D).
>|||SELECT DISTINCT
COALESCE(P1.product, P2.product)
FROM P1
FULL JOIN P2
ON P1.product = P2.product
--
David Portas
SQL Server MVP
--|||Thanks, you're graet David.
"David Portas" wrote:

> SELECT DISTINCT
> COALESCE(P1.product, P2.product)
> FROM P1
> FULL JOIN P2
> ON P1.product = P2.product
> --
> David Portas
> SQL Server MVP
> --
>
>sql

No comments:

Post a Comment