Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Countif function [duplicate]

Tags:

sql

I have a table like below

Type of Station | Broadcast Management
----------------+-------------------------
Full Power      | Sinclair Broadcast Group
Full Power      | Sinclair Broadcast Group
LPTV cable      | Sinclair Broadcast Group
LPTV no cable   | Sinclair Broadcast Group

Now I want to execute a query that will bring result looks like below

Broadcast Management       | Full Power | LPTV cable | LPTV no cable
---------------------------+------------+------------+--------------
Sinclair Broadcast Group   |  2         |     1      |  1

Can anyone please help me how to write this query

like image 355
Arfater Rahman Avatar asked Jun 29 '13 17:06

Arfater Rahman


People also ask

Does count count duplicates SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.

Does count remove duplicates SQL?

Yes, when using the COUNT() function on a column in SQL, it will include duplicate values by default. It essentially counts all rows for which there is a value in the column. If you wanted to count only the unique values in a column, then you can utilize the DISTINCT clause within the COUNT() function.


1 Answers

There is no single SUMIF or COUNTIF.

But you do have SUMor COUNT and an IF using CASE...

SELECT
  [Broadcast Management],
  SUM(CASE WHEN [Type of Station] = 'Full Power'    THEN 1 ELSE 0 END)   AS [Full Power],
  SUM(CASE WHEN [Type of Station] = 'LPTV Cable'    THEN 1 ELSE 0 END)   AS [LPTV Cable],
  SUM(CASE WHEN [Type of Station] = 'LPTV No Cable' THEN 1 ELSE 0 END)   AS [LPTV No Cable]
FROM
  yourTable
GROUP BY
  [Broadcast Management]

For counts, you can make the ELSE return NULL as the count of 1, 2, 4, NULL is 3.

like image 128
MatBailie Avatar answered Oct 21 '22 04:10

MatBailie