How can I get the COUNT() of the specific field depends on the value of the field? For example I have the field typeOfAssistance , in the query below I got the total numbers of the typeOfAssistance but I have different values in it which is financial medical and burial, How can I add custom column that will divide the total value depends on the value?
SELECT date,COUNT(*) AS num
FROM requests
WHERE date BETWEEN DATE_ADD(CURDATE(),INTERVAL -20 DAY) AND CURDATE()
GROUP BY date
desired output:
date | financial | burial | medical | total
2014-04-25 | 1 | 2 | 3 | 6
Thanks. Sorry for the explanation. :)
Typically for something like that I would use SUM rather than COUNT for the item breakdowns.
Something like
SELECT date,
SUM(CASE WHEN typeOfAssistance = 'financial' THEN 1 ELSE 0 END) AS financial,
SUM(CASE WHEN typeOfAssistance = 'burial' THEN 1 ELSE 0 END) AS burial,
SUM(CASE WHEN typeOfAssistance = 'medical' THEN 1 ELSE 0 END) AS medical,
COUNT(1) AS Total
FROM requests
GROUP BY date
Related
I think what I need isn't that complex but I've already spent days playing with SQL queries.
Here my basic table structure
id | status | date
1 | active | 2020-01-02
2 | complete | 2020-01-03
3 | complete | 2020-01-03
4 | active | 2020-01-03
I'm trying to achieve this result on my query, grouping the result by date then counting the following
total - based on total row count by date,
active - based on active status by date,
complete - based on complete status by date
this is my desired format below
[
{
total: 1,
active: 1,
completed: 0,
date: "2020-01-02"
},
{
total: 3,
active: 1,
completed: 2,
date: "2020-01-03"
}
]
This runs on Laravel and I'm trying to play with Eloquent as well as the Query builder
but no success
$leadReport = Lead::select(
DB::raw('count(id) as `total`'),
//DB::raw('count(CASE WHEN `status` = `active ) as `active`'),
//DB::raw('count(CASE WHEN `status` = `complete`) as `completed`'),
DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d') as date")
)->where('iso','au')->groupBy('date')->orderBy('date')->get();
return $leadReport;
Appreciate any help
EDIT
just want to thank you #Yazan for the recommended query by using SUM,
I manage to use it on laravel query builder like below
$leadSummary = Lead::select(
DB::raw("Sum(CASE WHEN status = 'completed' AND json_unquote(json_extract(`lenders`, '$.current_status')) IN ('Settled', 'Funded') THEN 1 ELSE 0 END) AS settled"),
DB::raw("Sum(CASE WHEN status = 'completed' AND json_unquote(json_extract(`lenders`, '$.current_status')) NOT IN ('Settled', 'Funded') THEN 1 ELSE 0 END) AS rejected"),
DB::raw("Sum(CASE WHEN status = 'active'THEN 1 ELSE 0 END) AS active ")
)->where('iso','au')->get();
use sum instead of count like this
SELECT Count(id) AS total,
Sum(CASE
WHEN status = 'active' THEN 1
ELSE 0
END) AS active,
Sum(CASE
WHEN status = 'completed' THEN 1
ELSE 0
END) AS completed,
Date_format(date, '%Y-%m-%d') AS date
FROM MYtable
GROUP BY date
ORDER BY date;
im trying to make a column for month 1, 2 and 3 and put the invoice's total in that column. I have made that successfully, but then below there are more columns with zeroes for every column, aka it shows me the column for every invoice, but I want to get ONLY the invoices that have been made in month 1,2 and 3 and don't show the rest. How do I do that?
what I get:
invoice_id | total | firstMonth | secondMonth | thirdMonth |
1 33.4 0 0 33.4
2 3434.5 0 0 0 <=====
what I want:
invoice_id | total | firstMonth | secondMonth | thirdMonth |
1 33.4 0 0 33.4
Please learn about types. Single quotes should be used for string and date constants -- and not for column identifiers or numbers.
Then, I think you just want to filter the results correctly:
SELECT i.id AS invoice_ID , i.total AS TOTAL,
(CASE WHEN month(i.datetime) = 1 THEN ABS(i.total) ELSE 0 END) AS firstMonth,
(CASE WHEN month(i.datetime) = 2 THEN ABS(i.total) ELSE 0 END) AS secondMonth,
(CASE WHEN month(i.datetime) = 3 THEN ABS(i.total) ELSE 0 END) AS thirdMonth
FROM invoice i JOIN
store s
ON i.store_id = s.id JOIN
company c
ON s.company_id = c.id
WHERE c.name = 'RubberDuck' AND
i.datetime >= '2019-01-01' AND
i.date_time < '2019-04-01'
I have a table with columns
TicketID - ID of the ticket
AssignedTo - UserID of person to whom ticket is assigned
CreatedTime - Time when Ticket is received
HandleTime - Time when Ticket is picked up for handling
FinishTime - Time when Ticket is finished handling
I need to retrieve the following data grouped to individual AssignedTo ID:
AssignedTo
Picking Rate in the following ranges(both % and count)
<1 minutes
1-2 minutes
2-5 minutes
Closing Rate in the following ranges(both % and count)
same ranges as above
Total Tickets
I have come up with a initial query as
SELECT
User,
sum(case when PickupTime <=1 then 1 else 0 end) as range1,
sum(case when PickupTime <=2 then 1 else 0 end) as range2,
...
FROM
(SELECT
((HandleTime - CreatedTime)/60000) as PickupTime,
((FinishTime - CreatedTime)/60000) as CompletedTime,
AssignedTo as User
FROM
TicketTable
)T
GROUP BY
User
Here I am able to get only the Pickup range counts.I still need Pickup range percentages and also Closing range counts and percentages.How do I get them?
EDIT:
Let us consider a sample dataset and only two ranges <=1 and >1 and also consider time as minutes directly here whereas in original table its stored as timestamp.
TicketID | AssignedTo | CreatedTime | HandleTime | FinishTime
1 001 2 3 3
2 001 4 6 8
3 002 1 2 3
In the above table User 001 is assigned a total of 2 tickets and User 002 is assigned a total of 1 ticket.
The PickupTime and CompletedTime for the tickets are
TicketID | PickupTime | CompletedTime
1 1 1
2 2 4
3 1 2
So for User-001 out of the two tickets assigned to him, he has picked 1 ticket within 1 minute range and 1 greater than 1 minute range.So percentage of tickets within 1 minute range is 50% and over 1 minute range is 50% for him.Same applies with regards to CompletedTime and also to the User-002 too.
So the final result what i want is.
AssignedTo | Pickup_range1_count | Pickup_range2_count | Pickup_range1_percentage |
001 1 1 0.5
002 1 0 1
Pickup_range2_percentage | Complete_range1_count | Complete_range2_count |
0.5 1 1
0 0 1
Complete_range1_percentage | Complete_range2_percentage
0.5 0.5
0 1
According to your example you already almost got it. All you need is the ratio of the individual sums and the total sum (or the count would have done it to). Something like
SELECT AssignedTo,
sum(1) AllCount,
sum(CASE
WHEN HandleTime - CreatedTime <= 1
THEN 1
ELSE 0
END) Range1PickupCount,
sum(CASE
WHEN HandleTime - CreatedTime > 1
THEN 1
ELSE 0
END) Range2PickupCount,
...
sum(CASE
WHEN HandleTime - CreatedTime <= 1
THEN 1
ELSE 0
END) / sum(1) * 100 Range1PickupPercentage,
sum(CASE
WHEN HandleTime - CreatedTime > 1
THEN 1
ELSE 0
END) / sum(1) * 100 Range2PickupPercentage,
...
FROM Tickets
GROUP BY AssignedTo;
should be a valid demonstration and something you can continue upon.
(Disclaimer: Not tested at all, as no DDL and DML was provided.)
Having trouble wrapping my head around having an efficient "duplicate entries" select in a single query.
In the below example, duplicate StockNo can exist spanning multiple Date. I want to search StockNo for duplicate entries, and if at least 1 StockNo record is found within the Date current YEAR-MONTH, then I also need to select its partner that could exist in any other YEAR-MONTH. Is this possible?
Example Query:
SELECT * FROM `sales`
WHERE `StockNo` IN
(SELECT `StockNo` FROM `sales` GROUP BY `StockNo` HAVING COUNT(*) > 1)
AND `Date` LIKE '2016-11-%'
ORDER BY `StockNo`, `TransactionID`;
Example Data:
ID | StockNo | Date
1 | 1 | 2016-11-01
2 | 1 | 2016-11-10
3 | 2 | 2016-11-05
4 | 2 | 2016-10-29
5 | 3 | 2016-10-25
6 | 3 | 2016-10-15
With my example query and data, I have 3 pairs of duplicate entries. It's pretty obvious that I will only return 3 records (ID's 1, 2 & 3) due to AND Date LIKE '2016-11-%', however I need to return ID's 1, 2, 3, 4. I want to ignore ID's 5 & 6 because neither of them fall within the current month.
Hope that makes sense. Thanks for any help you can provide.
SELECT StockNo
FROM sales
GROUP BY StockNo
HAVING SUM(CASE WHEN DATE_FORMAT(Date, '%Y-%m') = '2016-11' THEN 1 ELSE 0 END) > 0
If you also want to retrieve the full records for those matching stock numbers in the above query, you can just add a join:
SELECT s1.*
FROM sales s1
INNER JOIN
(
SELECT StockNo
FROM sales
GROUP BY StockNo
HAVING SUM(CASE WHEN DATE_FORMAT(Date, '%Y-%m') = '2016-11' THEN 1 ELSE 0 END) > 0
) s2
ON s1.StockNo = s2.StockNo
Demo here:
SQLFiddle
Thank you very much Tim for pointing me in the right direction. Your answer was close but it still only returned records from the current month and in the end I used the following query:
SELECT s1.* FROM `sales` s1
INNER JOIN
(
SELECT * FROM `sales` GROUP BY `StockNo` HAVING COUNT(`StockNo`) > 1
AND SUM(CASE WHEN DATE_FORMAT(`Date`, '%Y-%m')='2016-11' THEN 1 ELSE 0 END) > 0
) s2
ON s1.StockNo=s2.StockNo
This one had been eluding me for some time.
I have a lot of table and i need to get the gross income of a movie, now my problem is i don't know how to get the sum of first week only of a movie.
This is what i need.
+-------------------------------------------+
| title | Week one | Week one |
| | (Wed-Sun) | (Mon-Tue) |
+-------------------------------------------+
| title 1 | 50000 | 10000 |
+-------------------------------------------+
If the starting show of a movie is wed then i should make 3 column, first column is title, second column is the wed-sun and third is mon-tue.
Is this possible to query like select movie, sum(wed-sun), sum(mon-tue)
Thanks in advance
This is my answer based on how I understand your question.
SELECT movie, sum(wed-sun), sum(mon-tue) CONVERT(date, getdate()) as day
FROM thetable
WHERE thedate(BETWEEN first AND last)
GROUP BY day
You can user DAYOFWEEK() if you are using date type for that. See http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_dayofweek
For week days from mon-tue
SUM(CASE WHEN DAYOFWEEK(DATE)=2 THEN 1 WHEN DAYOFWEEK(DATE)=3 THEN 1 ELSE 0 END)
For week days from wed-sun
SUM(CASE WHEN DAYOFWEEK(DATE)=4 THEN 1 WHEN DAYOFWEEK(DATE)=5 THEN 1 WHEN DAYOFWEEK(DATE)=6 THEN 1 WHEN DAYOFWEEK(DATE)=7 THEN 1 WHEN DAYOFWEEK(DATE)=1 THEN 1 ELSE 0 END)
If you use WEEKDAY instead of DAYOFWEEK you can shorten the case statements:
SELECT
movie_id,
title,
SUM(CASE WHEN WEEKDAY(date_field) < 2 THEN field_to_sum ELSE 0 END) `mon-tue`,
SUM(CASE WHEN WEEKDAY(date_field) > 1 THEN field_to_sum ELSE 0 END) `wed-sun`
FROM
movies
/* optional WHERE */
GROUP_BY movie_id
Obviously you want WEEKDAY FUNCTION, it returns the weekday index starting from 0-Monday.
Assume you have table Movies with title and starting_show_date columns, and value_table with action_date and amount columns.
You can sum amount by splitting amounts to two parts like this:
select
movies.title,
sum(case when value_table.action_date
< dateadd(movies.starting_show_date , interval 7 -WEEKDAY(movies.starting_show_date) day)
then value_table.amount else 0 end) as FirstWeek,
sum(case when value_table.action_date
>= dateadd(movies.starting_show_date , interval 7 -WEEKDAY(movies.starting_show_date) day)
then value_table.amount else 0 end) as OtherWeeks
from
movies
inner join
value_table
on
movies.id = value_table.movie_id
group by
movies.title