here is my data,
Table 1:
STORAGE HANDLING TOTAL BILLING
--------------------------------------
1300 10900
0 10950
0 6000
0 5950
Table 2:
LINER REVENUE
---------------
1300
250
3000
200
I need to calculate Total Billing:
I tried with this code.
UPDATE [dbo].[FCLOverall] SET [Total Revenue] = SELECT SUM([STORAGE]), SUM([HANDLING]), SUM([LINER Revenue])
FROM (SELECT [STORAGE], [HANDLING],[Container No]
FROM [dbo].[FCLOverall]
UNION ALL
SELECT [Container No],[LINER Revenue]
FROM [dbo].[FCL_Child])
It is throwing some error missing brackets and invalid keyword select. is the query is right or wrong?
Can someone guide a query how to calculate on this?
does you find something below
UPDATE [dbo].[FCLOverall]
SET [Total Revenue] =
(SELECT SUM([STORAGE])+ SUM([HANDLING]) + SUM([LINER Revenue] ) as s
FROM (
SELECT [Container No],[STORAGE], [HANDLING],0
FROM [dbo].[FCLOverall]
UNION ALL
SELECT [Container No],0,0,[LINER Revenue]
FROM [dbo].[FCL_Child]
) t )
Give this a try based on the assumption that Container No is key field.
UPDATE U
SET U.[Total Revenue] = COALESCE(U.Storage,0) + COALESCE(U.Handling,0) + COALESCE(FCLC.[Liner Revenue],0)
FROM dbo.FCLOverall AS U
INNER JOIN dbo.FCL_Child AS FCLC
ON U.[Container No] = FCLC.[Container No]
Try this:
UPDATE FO
SET [FO.Total Revenue] = ISNULL(FO.[STORAGE], 0) + ISNULL(FO.[HANDLING], 0) + ISNULL(FC.[LINER Revenue],0)
FROM [dbo].[FCLOverall] AS FO
INNER JOIN [dbo].[FCL_Child] FC on FO.[FO.Container No] = FC.[Container No]
Related
I have struggled to find a solution to this problem, so any help would be hugely appreciated.
I have two tables, lets call one table_a and one table_b, representing two possible sources of customer orders. They both contain a field called "customer_number" which I am using to outer join table_b to table_a. I am then calculating an average customer order size given the two tables.
Where i struggle is where a customer has an entry in either table, but not in both. Then my average calc returns NULL.
Table_a:
Customer Number
Total Online Orders
123456789
1350
987654321
650
Table_b:
Customer Number
Total InStore Orders
123456789
350
So basically the second customer does not have an entry in table_b.
My code as follows:
select distinct
a.[customer number],
a.[Total Online Orders],
b.[Total InStore Orders],
coalesce(a.[Total Online Orders] + b.[Total InStore Orders]) / 2 as [Average Order Size]
from table_a a
full outer join table_b b on a.[customer number]=b.[customer number]
Results table:
Customer Number
Total Online Orders
Total InStore Orders
Average Order Size
123456789
1350
350
850
987654321
650
NULL
NULL
I basically want the results table to show 650 for customer 987654321. Any ideas what I am doing wrong?
thanks!
You can use the brute force method:
( coalesce(a.[Total Online Orders], 0) + coalesce(b.[Total InStore Orders], 0)) /
nullif(case when a.[Total Online Orders] is not null then 1 else 0 end +
case when b.[Total InStore Orders] is not null then 1 else 0 end, 0)
)
) as [Average Order Size]
Use COALESCE() for the values of the 2 columns twice:
(
coalesce(a.[Total Online Orders], b.[Total InStore Orders]) +
coalesce(b.[Total InStore Orders], a.[Total Online Orders])
) / 2 as [Average Order Size]
Consider UNION as well, which handles a few other cases too, especially where customer number isn't necessarily unique in each table:
WITH cte (xtype, [customer number], order_amt) AS (
select 1 AS xtype, [customer number], [Total Online Orders] FROM table_a UNION ALL
select 2 AS xtype, [customer number], [Total InStore Orders] FROM table_b
)
SELECT [customer number]
, SUM(CASE WHEN xtype = 1 THEN order_amt ELSE 0 END) AS [Total Online Orders]
, SUM(CASE WHEN xtype = 2 THEN order_amt ELSE 0 END) AS [Total InStore Orders]
, AVG(order_amt) AS [Average Order Size]
FROM cte
GROUP BY [customer number]
ORDER BY [customer number]
;
I am trying to make an interest calculation for a loan. I have 2 tables, first table is the loan table that contains the loan amount, interest rate and other data. But interest rate changes daily and is stored on another table. So interest rate must be taken from loan tbl only if a payment is made the same day that loan is created.
Also I need to have amount remained after every payment that is store on tbl payment. So on every payment I need to fill the columns on table payment below. I tried to create a SQL statement to calculate interest rate and another to calculate the amount remained after the payment but cant combine them in one insert statement.
Example for loanid=1 , pay amount=$1000, loanid=29
SELECT
1, 1000 , date(),
(IIF(NOT ISNULL(t1.dailyinterest), t1.dailyinterest, t2.interestrate)
FROM
daily AS t1
RIGHT JOIN
loanable AS t2 ON (t1.loanid = t2.loanid AND t1.data = date())
WHERE
t2.loanid = 29)
SELECT
IIF(NOT ISNULL(pay.amountremained_tobepayed), pay.amountremained_tobepayed, 50000)
FROM
payment AS pay
RIGHT JOIN
(SELECT MAX(paymentid) AS id
FROM payment
WHERE loanid = 29) AS max2 ON pay.paymentid = max2.id
loan table
loanid
clientid
loanamount
interestrate
date
1
1
50000
0.2
05/04/20
daily interest table
clientid
loanid
date
dailyinterest
1
1
06/04/20
0.3
1
1
07/04/20
0.31
1
1
08/04/20
0.32
payment table
paymenid
loanid
amountpayed
paid_date
paid_interest
paid_pricipal
amountremained_tobepayed
Your query could look something like this.
parameters [loan id] int,
[client id] int,
[payment date] datetime,
[payment amount] currency;
insert into [payment table] (
-- payment table column names go here
)
select
-- parameters, names of columns in loan_table and
-- daily_interest_table, and calculated values go here
from loan_table
inner join daily_interest_table
on loan_table.loanid = daily_interest_table.loanid
and loan_table.clientid = daily_interest_table.clientid
where loan_table.loanid = [loan id]
and loan_table.clientid = [client id]
and daily_interest_table.date = [payment date];
I wrote below sql code but giving me error Syntax error missing operator in query
select 29, 1000 , date(), IIF(not IsNull(t1.dailyinterest) ,t1.dailyinterest, t2.interestrate) * 1000/100 AS inte, 1000 - inte as principal, amtremained
FROM daily AS t1
RIGHT JOIN loant AS t2
ON (t1.loanid = t2.loanid and t1.data= date())
inner join
(select IIF(not IsNull(pay.remainedamount), pay.remainedamount, 50000) - principal as amtremained
FROM paymentt AS pay RIGHT JOIN
(SELECT max(paymentid) AS id FROM paymentt where loanid=29) AS max2 ON pay.paymentid=max2.id)
on pay.loanid=t1.loanid
Update [sheet1$]
SET [Status] = 'Greater than 100M'
WHERE [Available Balance in USD] > 100000000
AND [Main Category] = 'Free Cash' AND [Sub Category] <> 'abc'
Getting an error saying
datatype mismatch error
The data type of column [Available Balance in USD] is Text. I need to convert to Int and check. Does anyone know how to do that?
In SQL Server, you would use try_convert():
WHERE TRY_CONVERT(INT, [Available Balance in USD]) > 100000000
I have the following script, trying to count how many distinct customers are there , how many distinct orders , what is total of all orders under £15 and its's avg, total of orders above £20 and it's avg.
with consignments as
(select
[Sell-to Customer No_],
[Convert-to Document No_],
ic.[Shipping Agent Service Code],
[Pick Completed DateTime] as [Shipped DateTime],
ROUND((ic.[Amount Including VAT] + ic.Postage + ic.[Gift Wrap Price] +
ic.[Handling Fee] + ic.[Personalisation Fee]),2) as [Document Amount]
from dbo.[Temp$Consignment] ic inner join [dbo].
[Temp$Order] oh
on ic.[Owner Header GuID]=oh.[Order Guid]
where ic.[Shipping Agent Service Code]='secstan' and ic.[Pick Completed
DateTime] >= '2016-11-01T00:00:00.000' AND
ic.[Pick Completed DateTime] <= '2016-11-30T23:59:55.000' ),summary as
(select *,CASE WHEN [Document Amount] > 15 THEN 1 ELSE 0 END as 'Over15'
from consignments )select * from summary
I have working script like below, but as I am new to sql I am bit confused how to convert above script to below.
select amountclass,[Shipping Agent Service Code],
count(distinct [Sell-to Customer No_]) as Total_customers,
count(*) as Total_orders,
sum([Amount]) as total_revenue,
avg([Amount] * 1.0) as AOV
from
(
select [Sell-to Customer No_], oh.[Original Order No_], [Amount],ic.
[Shipping Agent Service Code],
case when [Amount] <= 20 then 'Under_20'
else 'Over_20'
end as amountclass
from [TBW_BI].[dbo].[Temp$Order] oh INNER JOIN [TBW_BI].[dbo].
[Temp$Consignment] IC
ON IC.[Owner Header GuID]=OH.[Order Guid]
where[order date] >= '2016-09-01' AND
[order date] <= '2016-09-30' AND [COUNTRY]='UNITED KINGDOM' and
[document type] like 'ord%' and ic.[Shipping Agent Service
Code]='secstan'
) dt
group by amountclass,[Shipping Agent Service Code]
order by amountclass,[Shipping Agent Service Code]
It looks like you have a query with a 2 Common Table Expressions (CTE) and you want to convert the CTE to a derived table. First, we can eliminate one of the CTEs.
summary as
(select *,CASE WHEN [Document Amount] > 15 THEN 1 ELSE 0 END as 'Over15'
from consignments )
select * from summary
The CTE for summary is unnecessary. We can convert that code to this:
select *,CASE WHEN [Document Amount] > 15 THEN 1 ELSE 0 END as 'Over15'
from consignments
Now, instead of using the consignments CTE; we can copy the sql code within it to create a derived table.
select *,CASE WHEN [Document Amount] > 15 THEN 1 ELSE 0 END as 'Over15'
from (
select [Sell-to Customer No_],
[Convert-to Document No_],
ic.[Shipping Agent Service Code],
[Pick Completed DateTime] as [Shipped DateTime],
ROUND((ic.[Amount Including VAT] + ic.Postage + ic.[Gift Wrap Price] +
ic.[Handling Fee] + ic.[Personalisation Fee]),2) as [Document Amount]
from dbo.[Temp$Consignment] ic
inner join [dbo].[Temp$Order] oh on ic.[Owner Header GuID]=oh.[Order Guid]
where ic.[Shipping Agent Service Code]='secstan'
and ic.[Pick Completed
DateTime] >= '2016-11-01T00:00:00.000'
AND
ic.[Pick Completed DateTime] <= '2016-11-30T23:59:55.000' ) as t
I want to calculate running total in one of my access queries using SQL ( no DSUM please).
I have 3 fields in my existing query Namely SubCategoryID, brand and Revenue and would like to calculate the running total of the revenue under each SubCategory.
I've written a query for it, but there is some error and I cant find a way to correct it.
SELECT x.SubCategoryID
,x.brand
,x.[Avg Revenue]
( Select Sum(x2.[Avg Revenue])
From FROM [BrandRevenue] x2
Where x2.[SubCategoryID] = x.[SubCategoryID] AND x2.[Avg Revenue] <= x.[Avg Revenue]) As [Running Sum]
FROM (Select SubCategoryID, brand, [Avg Revenue]
FROM [BrandRevenue]
Order BY SubCategoryID, [Avg Revenue] DESC) As x
Group BY x.SubCategoryID, x.brand, x.[Avg Revenue];
Thanks for helping :)
You have repeated "From" in your correlated subquery:
( Select Sum(x2.[Avg Revenue])
From FROM [BrandRevenue] x2
...
I don't think you need the subquery in the from clause, or the GROUP BY either. I think this will be better, and certainly simpler:
SELECT x.SubCategoryID,
x.brand,
x.[Avg Revenue],
( SELECT SUM(x2.[Avg Revenue])
FROM [BrandRevenue] x2
WHERE x2.[SubCategoryID] = x.[SubCategoryID]
AND x2.[Avg Revenue] <= x.[Avg Revenue]
) AS [Running Sum]
FROM BrandRevenue AS x
ORDER BY x.SubCategoryID, x.[Avg Revenue] DESC;
ADDENUM
I think to get around the problem of Brands having the same revenue you will need to add some additional logic to your correlated subquery:
SELECT x.SubCategoryID,
x.brand,
x.[Avg Revenue],
( SELECT SUM(x2.[Avg Revenue])
FROM [BrandRevenue] x2
WHERE x2.[SubCategoryID] = x.[SubCategoryID]
AND ( x2.[Avg Revenue] <= x.[Avg Revenue]
OR (x2.[Avg Revenue] = x.[Avg Revenue]
AND x2.Brand <= x.Brand
)
) AS [Running Sum]
FROM BrandRevenue AS x
ORDER BY x.SubCategoryID, x.[Avg Revenue] DESC, x.Brand;