Usually I feel pretty confident with SQL queries, however this one has me scratching my head. I feel like this -should- be a quick fix, but I'm just not seeing it.
I'm trying to do a count on multiple values on the same table, in one query.
Don't mind the "0000000000000000" it's just representing an empty byte array.
Is there an easy way to combine these queries?
SELECT COUNT(ssn)
FROM patients
WHERE ssn="0000000000000000";
SELECT COUNT(firstname)
FROM patients
WHERE firstname="0000000000000000"
SELECT COUNT(lastname)
FROM patients
WHERE lastname="0000000000000000"
etc...
In SQL, you can make a database query and use the COUNT function to get the number of rows for a particular group in the table. Here is the basic syntax: SELECT COUNT(column_name) FROM table_name; COUNT(column_name) will not include NULL values as part of the count.
Obviously, COUNT(DISTINCT) with multiple columns counts unique combinations of the specified columns' values. However, one other important point is that a tuple is counted only if none of the individual values in the tuple is null.
Using COUNT, without GROUP BY clause will return a total count of a number of rows present in the table. Adding GROUP BY, we can COUNT total occurrences for each unique value present in the column. we can use the following command to create a database called geeks.
SELECT SUM(CASE WHEN ssn = '0000000000000000' THEN 1 ELSE 0 END) AS ssn_count,
SUM(CASE WHEN firstname = '0000000000000000' THEN 1 ELSE 0 END) AS first_count,
SUM(CASE WHEN lastname = '0000000000000000' THEN 1 ELSE 0 END) AS last_count
FROM patients
WHERE ssn = '0000000000000000'
OR firstname = '0000000000000000'
OR lastname = '0000000000000000'
You can do something like this -
SELECT COUNT(ssn) AS patient_count, 'ssn' AS count_type
FROM patients
WHERE ssn="0000000000000000";
UNION
SELECT COUNT(firstname) AS patient_count, 'firstname' AS count_type
FROM patients
WHERE firstname="0000000000000000"
UNION
SELECT COUNT(lastname) AS patient_count, 'lastname' AS count_type
FROM patients
WHERE lastname="0000000000000000"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With