Ad
Division In Group By SQL Table
I have the following SQL code
SELECT (COUNT(*) filter (WHERE has_a)) AS count_a,
COUNT(*) AS total_count,
process_date
FROM(SELECT process_date::date AS process_date,
(CASE WHEN (columnA > 0) THEN true ELSE false END) AS has_a
FROM my_table)
temptable
GROUP BY process_date
LIMIT 5;
which gives the following table
I want to create a column called percent_a with value (count_a/total_count)*100
grouped by process_date
. E.g for row 1 the new column would have value 49.4 i.e. (1030/2085)*100.
I have tried
SELECT process_date,
((COUNT(*) filter (WHERE has_a))/COUNT(*) * 100) AS percent_a,
FROM(SELECT process_date::date AS process_date,
(CASE WHEN (columnA > 0) THEN true ELSE false END) AS has_a,
FROM my_table)
temptable
GROUP BY process_date
ORDER BY process_date DESC
LIMIT 1;
But this just gave 0s.
How can I create the column to display the % I want? I think something is happening with the GROUP BY
but I don't know how to fix it.
Ad
Answer
It's because count
returns an integer, you just need to cast it:
SELECT process_date,
(((COUNT(*) filter (WHERE has_balance))::DOUBLE PRECISION)/COUNT(*) * 100) AS percent_a,
FROM(SELECT process_date::date AS process_date,
(CASE WHEN (columnA > 0) THEN true ELSE false END) AS has_a,
FROM my_table)
temptable
GROUP BY process_date
ORDER BY process_date DESC
LIMIT 1;
Ad
source: stackoverflow.com
Related Questions
- → I can't do a foreign key, constraint error
- → How to implement DbDongle::convertTimestamps as workaround of invalid timestamps with MySql strict
- → MySQL error "Foreign key constraint is incorrectly formed"
- → Eloquent Multitable query
- → "Laravel 5.1" add user and project with userId
- → Database backup with custom code in laravel 5 and get the data upto 10 rows from per table in database
- → Laravel 5.1 QueryException when trying to delete a project
- → Using Array in '->where()' for Laravel Query Building
- → Chaining "Count of Columns" of a Method to Single Query Builder
- → Laravel Eloquent Joining Strange query
- → convert time using mysql laravel 5
- → How to update a column after an expiration date in MySQL?
- → Foreign key constraint fails on existing key
Ad