In a table xyz I have a row called components and a labref row which has labref number as shown here
Table xyz
labref component NDQA201303001 a NDQA201303001 a NDQA201303001 a NDQA201303001 a NDQA201303001 b NDQA201303001 b NDQA201303001 b NDQA201303001 b NDQA201303001 c NDQA201303001 c NDQA201303001 c NDQA201303001 c
I want to group the components then count the rows returned which equals to 3, I have written the below SQL query but it does not help achieve my goal instead it returns 4 for each component
SELECT DISTINCT component, COUNT( component ) FROM `xyz` WHERE labref = 'NDQA201303001' GROUP BY component
The query returns
Table xyz
labref component COUNT(component) NDQA201303001 a 4 NDQA201303001 b 4 NDQA201303001 c 4
What I want to achieve now is that from the above result, the rows are counted and 3 is returned as the number of rows, Any workaround is appreciated
So, if you want to count quantity of groups, not quantity of elements in each group, and return duplicate value to every group record in result table, you should use OVER() clause on you'r count function.
To count the number of rows, use the id column which stores unique values (in our example we use COUNT(id) ). Next, use the GROUP BY clause to group records according to columns (the GROUP BY category above). After using GROUP BY to filter records with aggregate functions like COUNT, use the HAVING clause.
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.
The SQL GROUP BY Statement The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.
Try this simple query without a sub-query:
SELECT COUNT(DISTINCT component) AS TotalRows FROM xyz WHERE labref = 'NDQA201303001';
You need to do -
SELECT COUNT(*) FROM ( SELECT DISTINCT component FROM `multiple_sample_assay_abc` WHERE labref = 'NDQA201303001' ) AS DerivedTableAlias
You can also avoid subquery as suggested by @hims056 here
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