Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to get a total count and a count of a subset?

I was trying to do this:

SELECT COUNT(*),
        (
            SELECT COUNT(*) FROM attend
            WHERE (DATEPART(WEEKDAY,start_date) = 2 OR DATEPART(WEEKDAY,start_date) = 6)
            AND empl_no = 12345
        )
        FROM attend as a
 WHERE empl_no = 12345

But this seems a little ugly. Is there a better way to do this?

like image 948
Abe Miessler Avatar asked Dec 11 '10 00:12

Abe Miessler


People also ask

How do you find the total count?

Use the COUNT function to get the number of entries in a number field that is in a range or array of numbers. For example, you can enter the following formula to count the numbers in the range A1:A20: =COUNT(A1:A20). In this example, if five of the cells in the range contain numbers, the result is 5.

Which is faster count 1 or count (*)?

The simple answer is no – there is no difference at all. The COUNT(*) function counts the total rows in the table, including the NULL values. The semantics for COUNT(1) differ slightly; we'll discuss them later. However, the results for COUNT(*) and COUNT(1) are identical.

How do you get the SUM of counts in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.


1 Answers

Use:

SELECT COUNT(*) AS total,
       SUM(CASE 
             WHEN DATEPART(WEEKDAY, t.start_date) IN (2,6) THEN 1 
             ELSE 0 
           END) AS weekday
  FROM ATTEND t
 WHERE t.empl_no = 12345
like image 106
nate c Avatar answered Sep 28 '22 07:09

nate c