1

I have a select statement which is returning me 5 columns (and it is taking 1-2 minutes) one column in this is color (i.e. only three colors Red, Blue and Yellow). Now I want to show the count of the number of rows having Red, Number of rows having Blue and No. of rows having yellow in the same select statement.

Select statement is this

enter image description here

and I want output like this

enter image description here

Any help ?

Zerotoinfinity
  • 6,290
  • 32
  • 130
  • 206
  • 1-2 minutes? How many tables and rows is it operating on? If you add the SQL statement to your post, that will help us help you. – Eric H Feb 08 '12 at 18:36

2 Answers2

1

You want this (For SQL Server 2005+):

SELECT  *, SUM(CASE WHEN Color = 'RED' THEN 1 ELSE 0 END) OVER() [RED],
        SUM(CASE WHEN Color = 'BLUE' THEN 1 ELSE 0 END) OVER() [BLUE],
        SUM(CASE WHEN Color = 'Yellow' THEN 1 ELSE 0 END) OVER() [Yellow]
FROM YourTable
Lamak
  • 69,480
  • 12
  • 108
  • 116
1

Using CTEs (Common Table Expressions):

; 
WITH cte AS
( SELECT ...
  ... your query here
) 
WITH grp AS
( SELECT 
        color
      , COUNT(*) AS cnt
  FROM
        cte
  GROUP BY
        color
) 
SELECT 
      cte.*
    , (SELECT cnt FROM grp WHERE color = 'Red')    AS Red
    , (SELECT cnt FROM grp WHERE color = 'Blue')   AS Blue
    , (SELECT cnt FROM grp WHERE color = 'Yellow') AS Yellow
FROM 
      cte
ypercubeᵀᴹ
  • 113,259
  • 19
  • 174
  • 235