Divide and sum in SQL - sql

I got this code and in this code I do a sum of the slow and fast driver. My Problem is I must divide this sum with the normal driver. I donĀ“t know how I can do a division in this statement:
Select *
FROM (
Select date as Datetime, tevent.name as Event, level = case
when levelname = 'High' then 'High'
when levelname = 'Normal' then 'Normal'
when shiftname = 'Low' then 'Low'
end, SUM(value) as sum
from tCount inner join tEvent ON tCount.eventid = tevent.id
where Name in ('Drive Fast', 'Drive Slow')
and date > getdate() -1
and tevent.Name in ('E01','E02','E03','E04','E05','E06','E07','E08')
and CalName = 'Drive'
group by tevent.name, date, levelname
) as s
PIVOT
(
SUM(sum)
FOR Event IN (E01,E02,E03,E04,E05,E06,E07,E08)
) as p
order by Datetime, level
And Then I put the same Select statement with the normal driver :
... from tCount inner join tEvent ON tCount.eventid = tevent.id
where Name in ('drive normal') ...
And I would like to make a division like this:
(Sum('drive fast' + 'drive slow')/Sum('drive normal')) * 100

There is a simpler way to include different cases in different sums inside a SQL statement: sum a case, like in the below calculation of percent:
Select ...
, SUM(case Name
when 'drive fast' then Value
when 'drive slow' then value
else 0 end)
/ SUM(case Name
when 'drive normal' then value
else 0 end) * 100 as percentage
from ...
where ...
group by ...;
As I lack data to test this code, I created a query on the CARS table SAS delivers as training material, implementing the same principle.
select Cylinders
, sum(case origin when 'USA' then EngineSize
when 'Asia' then EngineSize
else 0.0 end)
/ sum(case origin when 'Europe' then EngineSize
else 0.0 end)
* 100 as percentage
from sasHelp.cars
where Cylinders in (4, 5, 6, 12)
group by Cylinders

Related

SQL/Oracle issue, I receive this error " REPORTS.WEK_MTD_BILL_SUM_HIST_T.BILL_CYCLE: invalid identifier at line 48" , is there anyway to fix this?

enter image description here
above is the image of the code, my objective is to have 4 columns demonstrating the prices for a bill cycle, and 4 columns demonstrating the average of all bill cycles one year before the initial bill cycle.
the first inner select works by itself and adds the 4 columns to the right in the picture below, the problem starts when I want to add second inner select the 4 columns for yearly average. initially I didn't have the "select * from", but I couldn't find a better way
the base of the problem is that I can't implement 2 Where clauses on the same column.
below is the snap shot of what I get from running only the first inner select.
enter image description here
I have tried union , join, cross join ... but none seem to work, one person suggested "window function" but I haven't worked with that yet.
this is the error below:
enter image description here
RAW CODE TEXT IS BELOW:
VARIABLE START_DATE CHAR
EXEC :START_DATE :=''
VARIABLE END_DATE CHAR
EXEC :END_DATE=''
select * from
(SELECT
"REPORTS"."WEK_MTD_BILL_SUM_HIST_T"."BILL_CYCLE",
"REPORTS"."WEK_MTD_BILL_SUM_HIST_T"."MTD_TOT" AS NET_TOTAL,
SUM(
SUM(
CASE WHEN "REPORTS"."WEK_MTD_BILL_SUM_HIST_T"."BLI_TYPE" = 'Charges'
THEN "WEK_MTD_BILL_SUM_HIST_T"."MTD_TOT" END)) OVER() AS TOTAL_CHARGES,
SUM(
SUM(
CASE WHEN "REPORTS"."WEK_MTD_BILL_SUM_HIST_T"."BLI_TYPE" = 'Credits'
THEN "WEK_MTD_BILL_SUM_HIST_T"."MTD_TOT" END)) OVER() AS TOTAL_CREDIT,
SUM(
SUM(
CASE WHEN "REPORTS"."WEK_MTD_BILL_SUM_HIST_T"."BLI_TYPE" = 'Previous Weekly Billing Net Total'
THEN "WEK_MTD_BILL_SUM_HIST_T"."MTD_TOT" END)) OVER() AS PRV_INVOICED,
SUM(
SUM(
CASE WHEN "REPORTS"."WEK_MTD_BILL_SUM_HIST_T"."BLI_TYPE" = 'Total Due / Receivable'
THEN "WEK_MTD_BILL_SUM_HIST_T"."MTD_TOT"
ELSE 0 END)) OVER() AS Net_Due_Total
FROM "REPORTS"."WEK_MTD_BILL_SUM_HIST_T"),
(SELECT
"REPORTS"."WEK_MTD_BILL_SUM_HIST_T"."BILL_CYCLE",
"REPORTS"."WEK_MTD_BILL_SUM_HIST_T"."MTD_TOT" AS NET_TOTAL,
(SUM(
SUM(
CASE WHEN "REPORTS"."WEK_MTD_BILL_SUM_HIST_T"."BLI_TYPE" = 'Total Due / Receivable' AND ( "REPORTS"."WEK_MTD_BILL_SUM_HIST_T"."BILL_CYCLE" BETWEEN '1-JAN-2022 4' AND :END_DATE)
THEN "WEK_MTD_BILL_SUM_HIST_T"."MTD_TOT" ELSE 0 END)) OVER()/COUNT(DISTINCT(BILL_CYCLE))) AS X
FROM
"REPORTS"."WEK_MTD_BILL_SUM_HIST_T"
WHERE
("REPORTS"."WEK_MTD_BILL_SUM_HIST_T"."BILL_CYCLE" BETWEEN :START_DATE AND :END_DATE )
)
GROUP BY
"REPORTS"."WEK_MTD_BILL_SUM_HIST_T"."MTD_TOT" ,
"REPORTS"."WEK_MTD_BILL_SUM_HIST_T"."BILL_CYCLE"
;

How to use multiple where clause in one sql query

Hello guys i need to use mutiple where clause in one sql query as follows but it can't work please help me.
select (select count(total) as 'studentMarks1' from School where total <60 ),
(select count(total) as 'studentMarks2' from School where total >80 )
from School
where Id = '8'
You rather need to use CASE statement like
select SUM(case when total < 60 then 1 else 0 end) as 'studentMarks1',
sum(case when total > 80 then 1 else 0 end) as 'studentMarks2'
from School
where Id = '8'
You cau usually do this with an appropriate CASE statement:
SELECT COUNT(CASE WHEN total < 60 then 1 else NULL END)
, COUNT(CASE WHEN total > 80 then 1 else NULL END)
FROM School
WHERE ID = '8'

SSRS: how to get top 3 in order Z to A

I try to get in my diagram the top 3 of the worst value in SSRS:
my Code:
SELECT *
FROM (
Select top 3
intervaldate as Datum
,Name
,teamname as Team
,SUM(case when CounterName = 'Blown away' then calculationUnits else 0 end) as Blown
,Sum(case when CounterName = 'Thrown away' then calculationUnits else 0 end) as Thrown
,Sum(case when CounterName = 'total' then calculationUnits else 0 end) as Total
from Counting
where IntervalDate >= dateadd(day,datediff(day,1,GETDATE()),0)
AND IntervalDate < dateadd(day,datediff(day,0,GETDATE()),0)
and Name in (Select SystemID from tSystemView where SystemViewID = 2)
group by intervaldate, teamName, Name
) c
Expression of the diagram:
=Sum(Fields!Blown.Value + Fields!Thrown.Value) / Sum(Fields!Total.Value) * 100
And I sorted it from highest to lowest
But it does not show me the right order.
If I choose every "Name" then it shows me other value then the top 3:
all Names with value:
top 3:
It's because your top 3 statement is in the SQL while your sort is in the report. Without an order by SQL picks the top 3 random records. Also, unless there is more SQL you are not showing, the outer select is unnecessary. Add an order by <column> desc below your group by.
with Calcs as
(
select intervaldate as Datum,
Name,
TeamName,
SUM(case when CounterName = 'Blown away' then calculationUnits else 0 end) as Blown,
Sum(case when CounterName = 'Thrown away' then calculationUnits else 0 end) as Thrown,
Sum(case when CounterName = 'total' then calculationUnits else 0 end) as Total
from Counting
where IntervalDate >= dateadd(day,datediff(day,1,GETDATE()),0)
AND IntervalDate < dateadd(day,datediff(day,0,GETDATE()),0)
and Name in (Select SystemID from tSystemView where SystemViewID = 2)
group by intervaldate, teamName, Name
)
select b.*
from
(
select a.*, row_number() over (order by (Blown + Thrown)/Total desc) as R_Ord -- Change between ASC/DESC depending on needs
from Calcs a
) b
where R_Ord <=3

Sql ISNULL condition in Sql Pivot and Sql case

I searched for many solutions on SO and elsewhere but couldn't quite understand how to write a query for my problem.
Anyway my query looks like below
SELECT * FROM
(
SELECT Id, Date, Name, Amount,
CASE
WHEN DATEDIFF(DAY,Date,GETDATE()) <=0
THEN 'Current'
WHEN DATEDIFF(DAY,Date,GETDATE()) <30
THEN 'Due30'
WHEN DATEDIFF(DAY,Date,GETDATE()) <60
THEN 'Due60'
ELSE 'Due90'
END AS [Age]
FROM Statement
WHERE (Amount <> 0)
) AS S
PIVOT
(
SUM(Amount)
FOR[Age] IN ([Current],[Due30],[Due60],[Due90])
) P
and the result looks like this
Id Date Name Current Due30 Due60 Due90
----------- ---------- --------------------------------------------
1 2016-04-03 Alan NULL NULL NULL 110.00
2 2016-05-02 TC NULL NULL 30.00 NULL
where should i insert IsNull condition to be able to remove the null in the result and add a zero there.
I tried inserting IsNull in the pivot query but we all know that is not meant to work
You have to add it repetitively in the final SELECT, when you replace the SELECT * (which should only exist in ad-hoc queries or EXISTS tests) with the column list:
SELECT
Id,
Date,
Name,
COALESCE([Current],0) as [Current],
COALESCE(Due30,0) as Due30,
COALESCE(Due60,0) as Due60,
COALESCE(Due90,0) as Due90
FROM
(
SELECT Id, Date, Name, Amount,
CASE
WHEN DATEDIFF(DAY,Date,GETDATE()) <=0
THEN 'Current'
WHEN DATEDIFF(DAY,Date,GETDATE()) <30
THEN 'Due30'
WHEN DATEDIFF(DAY,Date,GETDATE()) <60
THEN 'Due60'
ELSE 'Due90'
END AS [Age]
FROM Statement
WHERE (Amount <> 0)
) AS S
PIVOT
(
SUM(Amount)
FOR[Age] IN ([Current],[Due30],[Due60],[Due90])
) P
I've also used COALESCE since it's generally the preferred option (ANSI standard, extends to more than two arguments, applies normal type precedence rules) instead of ISNULL.
SELECT Id
, [Date]
, Name
, [Current] = SUM(CASE WHEN val <= 0 THEN Amount ELSE 0 END)
, Due30 = SUM(CASE WHEN val < 30 THEN Amount ELSE 0 END)
, Due60 = SUM(CASE WHEN val < 60 THEN Amount ELSE 0 END)
, Due90 = SUM(CASE WHEN val >= 60 THEN Amount ELSE 0 END)
FROM dbo.[Statement] t
CROSS APPLY (
SELECT val = DATEDIFF(DAY, [Date], GETDATE())
) s
WHERE Amount <> 0
GROUP BY Id, [Date], Name

how can i set the alias of column`s sum value based on another column in same table in sql?

I have a table of Accounts, having columns:
Acc_Id, Transaction_TypeId, Amount
I want to get result as When Transaction_TypeId = 1 then Sum of Amount as 'Total Advance Payments'.
Else when Transaction_typeId = 2 then Sum of Amount as 'Total Reciepts'
Here is my SQL query:
SELECT SUM(Amount) AS 'Sum' , Transaction_TypeId INTO #temp1 FROM AccountDetailTable WHERE Account_MasterId = 1 GROUP BY Transaction_TypeId
SELECT Sum as 'Total Advance' from #temp1 WHERE #temp1.Transaction_TypeId = 1;
SELECT Sum as 'Total Cash Receipts' FROM #temp1 WHERE #temp1.Transaction_TypeId = 2;
DROP TABLE #temp1;
but this query returns me two different result sets. How can i get the values in same result sets?
Use a CASE expression:
SELECT SUM(CASE WHEN Transaction_TypeId = 1 THEN somecolumn END) as [Total Advance],
SUM(CASE WHEN Transaction_TypeId = 2 THEN somecolumn END) as [Total Cash Receipts]
FROM #temp1;
You should use CASE EXPRESSION like this:
SELECT
sum(case when #temp1.Transaction_TypeId = 1 then amount else 0 end) as 'Total Advance',
sum(case when #temp1.Transaction_TypeId = 2 then amount else 0 end) as 'Total Cash Receipts'
FROM #temp1