January 10, 2014 at 2:19 pm
Hi, I'd like to ask how you would get the OUTPUT below from the TABLE below:
TABLE:
id category
1 A
2 C
3 A
4 A
5 B
6 C
7 B
OUTPUT:
category count id's
A 3 1,3,4
B 2 5,7
C 2 2,6
The code would go something like:
Select category, count(*), .... as id's
from TABLE
group by category
I just need to find that .... part
January 10, 2014 at 2:31 pm
here's a testable solution you can adapt to your real data;
this gets each table, and a comma delimited list of column names.
use this as a model, and change it to match your data:
SELECT DISTINCT
t.name,
sq.Columns
FROM sys.tables t
JOIN (
SELECT OBJECT_ID,
Columns = STUFF((SELECT ',' + name
FROM sys.columns sc
WHERE sc.object_id = s.object_id
FOR XML PATH('')),1,1,'')
FROM sys.columns s
) sq ON t.object_id = sq.object_id
Lowell
January 13, 2014 at 5:48 am
Thanks Lowell, but wow that code is way beyond me.. I'm still noob at SQL
January 13, 2014 at 7:18 am
;WITH result (category,ids) AS (
SELECT category,
STUFF((SELECT ',' + CAST(b.id as varchar(10))
FROM b
WHERE b.category = a.category
FOR XML PATH('')),1,1,'')
FROM a
GROUP BY category)
SELECT category,(LEN(ids)-LEN(REPLACE(ids,',','')))+1 AS [count],ids
FROM result
ORDER BY category ASC
Far away is close at hand in the images of elsewhere.
Anon.
Viewing 4 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply