views:

52

answers:

3

I have a table with 5 columns: ID, Session1, Session2, Session3, Session4. What I want to do is to display the number of same items from each column. Same item can't appear in more than one column.

ID   Session1   Session2   Session3   Session4  
--   --------   --------   --------   --------  
1    Music      Web        Tech       Future  
2    Art        Articles   Search     Introduction  
3    Music      Books      Camera     Phone  
4    Music      Glass      Cup        Future  
5    Art        Books      Tech       Future  
6    Music      Glass      Cup        Phone

I want to display it like this on an asp.net page.

Music: 4
Art: 2
Web: 1
Articles: 1
Books: 2
Glass: 2
Tech: 2
Search: 1
Camera: 1
Cup: 2
Future: 3
introduction: 1
Phone: 2

how would I construct a sql query and display them on asp.net?

+1  A: 

You could simply use:

SELECT
    session1,
    COUNT(*)
FROM
    My_Table
GROUP BY
    session1
UNION ALL
SELECT
    session2,
    COUNT(*)
FROM
    My_Table
GROUP BY
    session2
...
Tom H.
Wrap this in a select with a ORDER BY, and you're done!
Mike M.
I can't really discern an order in his sample results. If it's ordered by the column then you would need to add a hard-coded value to each select so that you know from where it originated.
Tom H.
how do I display a total number for each item as in my example?
codeLearner
Ummm.... run the code? I'm not sure what you're asking.
Tom H.
what I mean is how do I display the results on a web page (asp.net)?
codeLearner
I'm not an ASP.NET developer so I can't provide you with that code, but if you're unable to do that and you expect to be using ASP.NET, you should probably pick up an introductory book on ASP or Google "ASP.NET tutorial" to get started.
Tom H.
+1  A: 

With SQL Server you could do something like this:

  SELECT Session, COUNT(*) FROM (
  SELECT Session1 AS Session FROM TableName
  UNION ALL
  SELECT Session2 AS Session FROM TableName
  UNION ALL
  SELECT Session3 AS Session FROM TableName
  UNION ALL
  SELECT Session4 AS Session FROM TableName) T1
  GROUP BY Session

It's not pretty, but it should work.

Darvis Lombardo
A: 

try:

  Select z.Val, Count(*) ValueCount
  From   (Select Distinct session1 val From Table Union
          Select Distinct session2 val From Table Union
          Select Distinct session3 val From Table Union
          Select Distinct session4 val From Table) Z
     Join Table t on Z.Val In (t.Session1, t.Session2, t.Session3, t.Session4)
  Group By z.Val
Charles Bretana