Groups | Blog | Home
all groups > sql server programming > march 2004 >

sql server programming : returning same row multiple times


Adam Machanic
3/17/2004 6:12:00 PM
SELECT myNumber FROM myTable WHERE myNumber > 4
UNION ALL
SELECT myNumber FROM myTable WHERE myNumber < 6

[quoted text, click to view]

msnews.microsoft.com
3/17/2004 11:03:43 PM
Hi,

Is there a way to return a row multiple times if it matches multiple
clauses?

For example, say i have a column called myNumber and one of the values in it
is 5. I can do this query...

SELECT myNumber FROM myTable WHERE myNumber > 4 OR myNumber < 6;

....and it will return a single 5. What i'm looking to do though is have the
number 5 returned twice because it matched both clauses. Is it possible to
do this within a single query?

Much thanks,
Mav

David Portas
3/17/2004 11:21:36 PM
You could try this:

SELECT T.mynumber
FROM MyTable AS T
JOIN (SELECT 1 UNION ALL SELECT 2) AS X(x)
ON (X.x = 1 AND T.myNumber > 4)
OR (X.x = 2 AND T.myNumber < 6)

But I don't really see the point of returning duplicates of the same row. A
more economical solution might be to add a count of the number of matches as
an extra column:

SELECT T.mynumber,
CASE WHEN mynumber > 4 THEN 1 ELSE 0 END +
CASE WHEN mynumber < 6 THEN 1 ELSE 0 END AS matches
FROM MyTable AS T

--
David Portas
SQL Server MVP
--

AddThis Social Bookmark Button