Groups | Blog | Home
all groups > sql server programming > november 2003 >

sql server programming : Query Please



Ramesh
11/27/2003 10:30:05 PM
Hi,

This is the scenario:

SELECT * FROM tblTest

(This is just a portion of records, actual list goes more
than 1000 records)
id partno filename
----------- ---------------
1 part1 file1
2 part2 file2
3 part3 file3
4 part3 file1

I want to retrieve the filename which has both
partno 'part1' and 'part3'
Here only file1 contains both the partno.

I know i can use a join like this to fetch the desired
output.
select a.filename from tbltest a,tbltest b where
a.partno = 'part1' and b.partno = 'part3'
and a.filename=b.filename

But the problem is that the number of partno may increase
for example
how to a filename containing 'part1', 'part2', 'part3'
and 'part4'

Can we build a dynamic query in such case.


Thanks in advance
Ramesh






Uri Dimant
11/28/2003 9:57:28 AM
Ramesh
CREATE TABLE #T
(
COL INT,
COL1 CHAR(1),
COL2 CHAR(2)
)

INSERT INTO #T VALUES (1,'A','11')
INSERT INTO #T VALUES (2,'B','22')
INSERT INTO #T VALUES (3,'C','33')
INSERT INTO #T VALUES (4,'C','11')

Select Distinct C.COL1, D.COL2
FROM
(
Select A.COL1, A.COL2
From #T A
Join #T B
On A.COL2= B.COL2
Where A.COL1 > B.COL1
) AS D
JOIN #T C ON C.COL2=D.COL2

DROP TABLE #T

Note : I assume if you choose 'a' and 'c' it will bring out 11
I know there are some circumstances you will need to elaborate the query.I
hope it will help you start with resolving the problem.




[quoted text, click to view]

Satya Rao
11/28/2003 12:35:25 PM

[quoted text, click to view]


What's the problem with

select filename, count(*) as cnt
from tblTest
group by filename
having cnt > 1



Roji. P. Thomas
11/28/2003 1:17:04 PM
If the number of parnos to check is varying
over each call, the best thing you can do is
to conevert them to a table variable.

Assuming that you are doing it inside as SP,
you can accept the parameters in a comma seperated list
and transform it to a table variable.

Then you can do a simple query as

Select A.FileName from tblTest A
INNER JOIN @tblPart B
ON A.PartNo = B.PartNo
AND A.Filename = @filename

HTH
--
Roji. P. Thomas
SQL Server Programmer ;)
________________________
[quoted text, click to view]

AddThis Social Bookmark Button