Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 A VERY EASY SELECT...

Author  Topic 

kfj_de
Starting Member

12 Posts

Posted - 2010-04-07 : 08:18:51
...but not for me. Especially not today, coming directly from the dentist to my desk.

We have a photodatabase.
The important part is:

File ID
Colour ID

Every File can have multiple colours. If it has multiple colours, it has multiple entries.

We want to put into the select statement the list of colours we are searching for with one or more parameters and get back a list of all the files that have ALL of the colours.

How would you do this?

Thanks for your help.

Asken
Starting Member

38 Posts

Posted - 2010-04-07 : 08:35:41
Can you explain some more with tables and some example data?


Reporting & Analysis Specialist
Go to Top of Page

Ifor
Aged Yak Warrior

700 Posts

Posted - 2010-04-07 : 08:54:51
Something like:

SELECT FileID
FROM YourTable
WHERE ColourID IN (1,2,5)
GROUP BY FileID
HAVING COUNT(DISTINCT ColourID) = 3

Go to Top of Page

DBA in the making
Aged Yak Warrior

638 Posts

Posted - 2010-04-07 : 09:07:19
Here's something to start you off...

-- You'll need to add this split function (Only run this part once).
-- Function is a modified version of:
-- http://weblogs.sqlteam.com/mladenp/archive/2007/05/22/60213.aspx
CREATE FUNCTION dbo.Split(@data VARCHAR(MAX), @delimiter VARCHAR(5))
RETURNS @t TABLE (data VARCHAR(MAX))
AS
BEGIN

DECLARE @textXML XML;
SELECT @textXML = CAST('<d>' + REPLACE(@data, @delimiter, '</d><d>') + '</d>' AS XML);

INSERT INTO @t(data)
SELECT T.split.value('.', 'nvarchar(max)') AS data
FROM @textXML.nodes('/d') T(split)

RETURN
END
GO


-- Start Creating dummy data
CREATE TABLE #FileColours (
FileID INT,
ColourID INT
)

INSERT INTO #FileColours
SELECT 1, 1
UNION ALL SELECT 1, 2
UNION ALL SELECT 1, 3
UNION ALL SELECT 1, 4
UNION ALL SELECT 2, 1
UNION ALL SELECT 2, 2
UNION ALL SELECT 3, 1
UNION ALL SELECT 3, 2
UNION ALL SELECT 4, 2
UNION ALL SELECT 4, 4
UNION ALL SELECT 5, 2
UNION ALL SELECT 5, 3
GO

-- Start query
DECLARE @Search VARCHAR(50) SET @Search = '4, 2'
DECLARE @Count INT
DECLARE @SearchTmp TABLE (ColourID INT)

INSERT INTO @SearchTmp
SELECT CAST(Data AS INT)
FROM dbo.Split(@Search, ',')

-- Remember how many rows were populated
SET @Count = @@ROWCOUNT

SELECT FileID
FROM #FileColours f
INNER JOIN @SearchTmp t
ON f.ColourID = t.ColourID
GROUP BY FileID
HAVING COUNT(*) = @Count
GO

-- Clean up.
DROP TABLE #FileColours
GO


There are 10 types of people in the world, those that understand binary, and those that don't.
Go to Top of Page

kfj_de
Starting Member

12 Posts

Posted - 2010-04-07 : 10:24:11
Both proposals work fine. This helps me a lot. Thank you very much.
Go to Top of Page
   

- Advertisement -