Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Count rows with specific values (Multiple in one query)

Tags:

tsql

count

I need some help with a T-SQL query. I want to count fields that have a special value(e.g. >1).

Assuming i have a table like:

IGrp | Item | Value1 | Value2 ############################# A    | I11  | 0.52   | 1.18 A    | I12  | 1.30   | 0.54 A    | I21  | 0.49   | 2.37 B    | I22  | 2.16   | 1.12 B    | I31  | 1.50   | 0.28 

I want a result like:

IGrp | V1High | V2High  ###################### A    | 1      | 2 B    | 2      | 1 

In my mind this should be going with this expression

SELECT IGrp, COUNT(Value1>1) AS V1High, COUNT(Value2>1) AS V2High FROM Tbl GROUP BY IGrp 

But that's not possible in T-SQL since the Count() does not take boolean values. So is it really the only possible way to do multiple queries with WHERE Value>1 and COUNT(*) and join them afterwards? Or is there a trick to accomplish the desired result?

Thanks in advance.

like image 822
Marks Avatar asked Jul 07 '10 10:07

Marks


People also ask

How do I count specific rows in SQL?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

How do you count rows in a SELECT statement?

To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.

How count selected query in SQL?

SELECT COUNT(*) FROM table_name; The COUNT(*) function will return the total number of items in that group including NULL values. The FROM clause in SQL specifies which table we want to list. You can also use the ALL keyword in the COUNT function.


2 Answers

SELECT IGrp,      COUNT(CASE WHEN Value1 > 1 THEN 1 ELSE NULL END) AS V1High,      COUNT(CASE WHEN Value2 > 1 THEN 1 ELSE NULL END) AS V2High  FROM Tbl GROUP BY IGrp 
like image 133
LukeH Avatar answered Sep 22 '22 02:09

LukeH


You can use the CASE statement:

SELECT IGrp,      SUM(CASE WHEN Value1>1 THEN 1 ELSE 0 END) AS V1High,      SUM(CASE WHEN Value2>1 THEN 1 ELSE 0 END) AS V2High  FROM Tbl GROUP BY IGrp  
like image 33
cjk Avatar answered Sep 21 '22 02:09

cjk