Multiple counts in one SQL query with grouping - sql

I want to run a query to get a count of open incident and closed incidents grouped by year and month, the below query works fine without the grouping, but once I add the group it will not work!
SELECT (SELECT COUNT(*) AS Opened FROM Incidents) AS Total
(SELECT COUNT(*) AS Solved FROM Incidents WHERE (MONTH(Closedate)=MONTH(Opendate))) AS Solved
GROUP BY YEAR(Incidents.Opendate)

You can use single a SELECT statement with CASE expression
SELECT YEAR(Incidents.Opendate) AS [Year],
MONTH(Incidents.Opendate) AS [Month],
COUNT(*) AS Total,
SUM(CASE WHEN MONTH(Closedate) = MONTH(Opendate) THEN 1 ELSE 0 END) AS Solved
FROM Incidents
GROUP BY YEAR(Incidents.Opendate), MONTH(Incidents.Opendate)

Try:
SELECT
(SELECT COUNT(*) FROM Incidents) as Total ,
(SELECT COUNT(*) FROM Incidents WHERE (Month(Closedate)=MONTH(Opendate))) as Solved
FROM Incidents
Group by YEAR(Incidents.Opendate)

I have managed to solve it, below is the query
select COUNT(CASE WHEN Month(Closedate)=Month(Opendate) then 1 else null end) AS closed,COUNT(*) AS Opened
from incidents
Group by Year(Opendate), Month(Opendate)
Order by Year(Opendate), Month(Opendate)

Related

How to add a condition for the query so that it can calculate the unique months and years in PostgreSQL

How can I write down the condition so that he counts the months for me from a certain client (redirect) and source (source)? I need to know how many invoices were issued, and this is counted by month, type January and February are 2 invoices, March April June 3 invoices, etc. I could write max instead of count, but this is not correct, since the client may appear in the middle of the year, for example in May, and he will have the values of the maximum month.
Here is my request:
select TA.redirect,
count(case when TA.source='zlat1' then extract(month from TA.date) else 0 end) number_of_accounts_zlat1,
count(case when TA.source='zlat2' then extract(month from TA.date) else 0 end) number_of_accounts_zlat2,
sum(TA.result_for_the_day) accrued
from total_accounts TA
group by TA.redirect
Here are tables and data + query and result ---->
https://dbfiddle.uk/?rdbms=postgres_14&fiddle=0bc8002e59b03afedeac8d1b8dfc98d1
insert into finace_base (redirect)
select distinct Ta.redirect /*this select will display those names that are not present
in FB if there is other info that u must add to insert then
just add , next to redirect and add whatever u like*/
from total_acounts TA
left join finace_base FB on TA.redirect=FB.redirect
where FB.redirect is null;
update finace_base FB
set zlat1=TA.zlat1,
zlat2=TA.zlat2,
accrued=TA.accrued
from (select TA.redirect,
count(*) filter ( where TA.source='zlat1' ) as zlat1,
count(*) filter ( where TA.source='zlat2' ) as zlat2,
sum(TA.accrued) as accrued
from(
select sum(TA.accrued) as accrued,
TA.date,
TA.redirect,
TA.source
from (select TA.result_for_the_day as accrued,
to_char(TA.date, 'yyyy-mm') as date,
TA.redirect,
TA.source
from total_accounts TA) TA
group by TA.redirect, TA.date, TA.source) TA
group by TA.redirect) TA
where FB.redirect=TA.redirect
i could not add it into comments cause it was too long essentialy you first run the insert into statement and then update it will only do inserts for redirects that are not added yet
select TA.redirect,
count(*) filter ( where TA.source='zlat1' ) as zlat1,
count(*) filter ( where TA.source='zlat2' ) as zlat2,
sum(TA.accrued)
from(
select sum(TA.accrued) as accrued,
TA.date,
TA.redirect,
TA.source
from (select TA.result_for_the_day as accrued,
to_char(TA.date, 'yyyy-mm') as date,
TA.redirect,
TA.source
from total_accounts TA) TA
group by TA.redirect, TA.date, TA.source) TA
group by TA.redirect
there you go thats the answer. giving back to comunity that i have taken :D

Trying to Divide a SUM with CASE by COUNT of Total Trips and return Percentage

I have Two Tables Trips & Users.
I am trying to write a SQL query to find the cancellation rate of requests with unbanned users (both client and driver must not be banned) each day between
"2013-10-01" and "2013-10-03". Round Cancellation Rate in a percentage output
So in my case if Total Trips is 4 and Cancellations is 2 then I want to see .50 or if 3 and 1 then .33
Here is what I was trying to do so far...
With CTE AS (
Select Request_at as [DAY],
SUM (CASE
When Status= 'cancelled_by_driver' or Status='cancelled_by_client' THEN 1
Else 0
END)
AS Cancellations,
Count(*) as TotalTrips
FROM Trips
Where Client_id NOT IN (SELECT [Users_id] FROM [Study].[dbo].[Users] Where Banned='YES' and Roll='Client') or Driver_id NOT IN (SELECT [Users_id] FROM [Study].[dbo].[Users] Where Banned='YES' and Roll='Driver')
Group By Request_at )
Select DAY, ((TotalTrips/Cancellations) *100) as CancellationRate
From CTE
But the Divide Function is not working. I am not sure how else to approach this.
This is an error I am getting.
Any help is appreciated.
Try this one:
With CTE AS (
Select Request_at as [DAY],
SUM (CASE
When Status= 'cancelled_by_driver' or Status='cancelled_by_client' THEN 1
Else 0
END)
AS Cancellations,
Count(*) as TotalTrips
FROM Trips
Where Client_id NOT IN (SELECT [Users_id] FROM [Study].[dbo].[Users] Where Banned='YES' and Roll='Client') or Driver_id NOT IN (SELECT [Users_id] FROM [Study].[dbo].[Users] Where Banned='YES' and Roll='Driver')
Group By Request_at )
Select DAY, convert(float, TotalTrips) * 100/NULLIF(Cancellations, 0) as CancellationRate
From CTE
Since we have to query users_id twice, we can put that in a CTE. No need of a second query to calculate the percent.
With Unbanned_users As (
Select [users_id] FROM [Study].[dbo].[Users]
Where Banned<>'YES'
)
Select Request_at as [DAY],
(100*Count(CASE When Status Like 'cancelled%' Then 1 End)+Count(*)/2)
/Count(*) as Cancellation_percent
From Trips t
Inner Join Unbanned_users cl ON t.client_id=cl.users_id
Inner Join Unbanned_users dr ON t.driver_id=dr.users_id
Group By Request_at
This assumes that all of the user ids in Trips, both client and driver, are defined in the Users table.
The +Count(*)/2 is to round 2 out of 3 to 67, instead of the truncated result of 66.

In SQL, how to you join multiple aggregate queries (count or sum specifically)?

I have a table that has the total number of different items per person. I am trying to create a new table that counts the number of people with a total of 0, 1, 2, 3, 4, 5, 6, and 7+ items grouped by company and year. I think I have individual queries that accomplish this task, but I can't get a join to work in order to fill the new table. The individual queries that seem to accomplish what I am trying to do are:
SELECT
Company,
YEAR(Date) as Year,
COUNT(*) as items0_Count
FROM table
WHERE items_total = 0
GROUP BY Company, YEAR(Date)
ORDER BY Company, YEAR(Date)
SELECT
Company,
YEAR(Date) as Year,
COUNT(*) as items1_Count
FROM table
WHERE items_total = 1
GROUP BY Company, YEAR(Date)
ORDER BY Company, YEAR(Date)
I would obviously have that same query 8 times with only the where statement changing in order to generate the counts for each case, but only included two here to keep the question short. Hope this makes sense, and thank you in advance for your help!
Use conditional aggregation:
SELECT Company, YEAR(Date) as Year,
SUM(CASE WHEN items_total = 0 THEN 1 ELSE 0 END) as items0_Count,
SUM(CASE WHEN items_total = 1 THEN 1 ELSE 0 END) as items2_Count
FROM table
GROUP BY Company, YEAR(Date)
ORDER BY Company, YEAR(Date);
You can add additional columns for whatever item counts you want.
Union all/ union the two queries you have. You'll get the desired else follow #GordonLinoff's answer.
Also as an easy way try this below
SELECT
Company,
YEAR(Date) as Year,
COUNT(*) as items0_Count
FROM table
WHERE items_total in (1,0)
GROUP BY Company, YEAR(Date)
ORDER BY Company, YEAR(Date)

Showing all results even using GROUP BY CLAUSE

Query :
How to sort by months ?
select format(datee,'mmm-yyyy') as [Months],sum(amount) as Amount
from ledger_broker
where ref_from like 'Purchase'
group by format(datee,'mmm-yyyy')
order by format(datee,'mmm-yyyy') desc
Output :
Try grouping by the same exact column which you select:
SELECT t.[Months], t.Amount
FROM
(
SELECT MONTH(datee) AS theMonth, YEAR(datee) AS theYear,
FORMAT(datee,'mmm-yyyy') AS [Months], SUM(amount) AS Amount
FROM ledger_transporter
WHERE ref_from LIKE 'Purchase'
GROUP BY MONTH(datee), YEAR(datee), FORMAT(datee, 'mmm-yyyy')
) t
ORDER BY t.theYear DESC, t.theMonth DESC
One way to order by date is to select the numeric month and year in your query.
change group by datee to group by format(datee,'mmm-yyyy').
select distinct format(datee,'mmm-yyyy') as [Months], sum(amount) as Amount
from ledger_transporter
where ref_from like 'Purchase'
group by format(datee,'mmm-yyyy')
order by Month(datee)
The reason is that your date, which I assume is say 01-FEB-2016 and 02-FEB-2016, is different and if you group by it, you will get 2 different records for it.
However, for format(datee,'mmm-yyyy'), ie FEB-2016, both of these dates are same. Hence the mismatch

SQL Grouping Issues

I'm attempting to write a query that will return any customer that has multiple work orders with these work orders falling on different days of the week. Every work order for each customer should be falling on the same day of the week so I want to know where this is not the case so I can fix it.
The name of the table is Core.WorkOrder, and it contains a column called CustomerId that specifies which customer each work order belongs to. There is a column called TimeWindowStart that can be used to see which day each work order falls on (I'm using DATENAME(weekday, TimeWindowStart) to do so).
Any ideas how to write this query? I'm stuck here.
Thanks!
Select ...
From WorkOrder As W
Where Exists (
Select 1
From WorkOrder As W1
And W1.CustomerId = W.CustomerId
And DatePart( dw, W1.TimeWindowStart ) <> DatePart( dw, W.TimeWindowStart )
)
SELECT *
FROM (
SELECT *,
COUNT(dp) OVER (PARTITION BY CustomerID) AS cnt
FROM (
SELECT DISTINCT CustomerID, DATEPART(dw, TimeWindowStart) AS dp
FROM workOrder
) q
) q
WHERE cnt >= 2
SELECT CustomerId,
MIN(DATENAME(weekday, TimeWindowStart)),
MAX(DATENAME(weekday, TimeWindowStart))
FROM Core.WorkOrder
GROUP BY CustomerId
HAVING MIN(DATENAME(weekday, TimeWindowStart)) != MAX(DATENAME(weekday, TimeWindowStart))