2

Lets say I have this table name "Stuff"

╔════╦═════╗
║ ID ║ VAL ║
╠════╬═════╣
║  1 ║ A   ║
║  2 ║ B   ║
║  3 ║ C   ║
║  4 ║ C   ║
║  5 ║ C   ║
║  6 ║ D   ║
║  7 ║ B   ║
║  8 ║ E   ║
╚════╩═════╝

I would like a query which can give me an output of where in the numbers the letters are repeating. Feel free to use any column name for the table.

Basically I want something that says "C" is reapeating on number 3, 4, and 5. "B" is repeating on number 2, and 7.

On my work I have thousand of rows. The example I gave you is very granular. If you need more information please let me know.

Taryn
  • 242,637
  • 56
  • 362
  • 405
Ash
  • 67
  • 1
  • 2
  • 9
  • What is your expected output? For example if you sort by val theb all the records with the same val will be grouped together so it will be easy to see what IDs each one of them relates to. I'm guessing this is not what you want. So what do you? – Andrew Savinykh Jun 27 '13 at 04:17

3 Answers3

3

You can try this one:

SELECT Val, Id =
    STUFF((SELECT ' , ' + CAST( Id as varchar(20))
           FROM Stuff b 
           WHERE b.Val = a.Val 
          FOR XML PATH('')), 1, 2, '')
FROM Stuff a
GROUP BY Val;

See this SQLFiddle

Output:

╔═════╦════════════╗
║ VAL ║     ID     ║
╠═════╬════════════╣
║ A   ║  1         ║
║ B   ║  2 , 7     ║
║ C   ║  3 , 4 , 5 ║
║ D   ║  6         ║
║ E   ║  8         ║
╚═════╩════════════╝
Himanshu
  • 31,810
  • 31
  • 111
  • 133
3

Try this one -

DECLARE @temp TABLE (Id INT, Val CHAR(1))
INSERT INTO @temp (Id, Val)
VALUES
    (1, 'A'),(2, 'B'),(3, 'C'),
    (4, 'C'),(5, 'C'),(6, 'D'),
    (7, 'B'),(8, 'E')

SELECT
      Val
    , RepeatValues = STUFF((
          SELECT ', ' + CAST(ID AS VARCHAR(10))
          FROM @temp a
          WHERE a.Val = b.Val
          FOR XML PATH ('')), 1, 2, '')
FROM @temp b
GROUP BY Val
Devart
  • 119,203
  • 23
  • 166
  • 186
2

try like this...

SELECT
      name
    , STUFF((
          SELECT ',' + CAST(ID AS VARCHAR(MAX))
          FROM [stuff] a
          WHERE a.name = b.name
          FOR XML PATH ('')), 1, 1, '') AS RepeatIds
FROM [stuff] b
GROUP BY name
Devart
  • 119,203
  • 23
  • 166
  • 186
Amit Singh
  • 8,039
  • 20
  • 29