How to calculate - sql

I have a table like this:
Item Qty Price A Price B
abc 5 36.00 0
qwe 8 0 48.00
zxc 6 12.00 0
poi 4 10.00 0
lkj 9 12.00 0
mnb 3 0 14.00
vfr 7 0 6.00
How can I sum the value using SQL ie. if Price A is zero, it will pick Price B. The expected results will be as follows :-
Item Value
abc 180.00
qwe 384.00
zxc 72.00
poi 40.00
lkj 36.00
mnb 42.00
vfr 42.00

SELECT
ITEM
, (Qty * [Price A]) + (Qty * [Price B]) AS Value
FROM
TableName

Use the following if A and B could be non-zero, and you only want to use price A when this occurs:
SELECT Item, CASE WHEN `Price A` != 0 THEN `Price A` * Qty
ELSE `Price B` * Qty
END AS Value
FROM table;

Why not do something like
SELECT SUM(Price A) FROM table; SELECT SUM(Price B) FROM table WHERE Price A = 0;
And then add the results together...

from the example above you could really just select priceA + priceB, since one or the other is always zero, otherwise... I am not quite sure this can be done in pure SQL...

Assuming both can be not null:
SELECT item, QTY * IF(PriceA!=0, PriceA, PriceB) AS VALUE from tableName;

Related

Athena count/Sum column divided by count/Sum column returns zero

I am trying to find percentage based on id column.
issue - I am trying to use count(column)/select count(column) from table which is giving output as 'Zero'
Table name - abc
When I use count function to achieve it is returning zero.
This below percentage query always returns zero, tried with many logic.
SELECT Count(id) id,
CASE
WHEN Cast(tax AS DOUBLE) BETWEEN 7.99 AND 9.99 THEN 'test'
WHEN Cast(tax AS DOUBLE) BETWEEN 10.00 AND 19.99 THEN 'test1'
WHEN Cast(tax AS DOUBLE) BETWEEN 20.00 AND 43.69 THEN 'test3'
ELSE '#N/A'
END AS "product_category",
FROM abc
WHERE Cast(tax AS DOUBLE) BETWEEN 10.00 AND 19.99
AND id IN
(
SELECT id
FROM abc
WHERE cast(tax double) BETWEEN 7.99 AND 9.99) )SELECT Count(id)/
(
SELECT Count(b.id)
FROM abc
WHERE Cast(tax AS DOUBLE) BETWEEN 7.99 AND 9.99)
FROM abc
if tax between
0 and 10 it is 'test1'
11 and 20 it is 'test2'
21 and 30 it is ;test3'
I am trying to find a output like below

SQL Insert two rows in other table based on If confition

I have 2 table which is DATA and MAIN. DATA table is the raw data extract from excel and MAIN table is the data after validation(few rules) have been made.
Rule:
If Amoun1<>'' and Amount2<>''.
Insert 2 row in MAIN table. The first row will have the value for Amount and Percentage from Amount2 & Percentage2 with TaxRateType = Taxable.
And the second row will have Amount and Percentage get from Amount1 & Percentage1 with TaxRateType = EXEMPT. The invoiceNo also will be add with '_1'
If Amount2<>'' and Amount1=''
Insert 1 row with Amount and Percentage from Amount2 & Percentage2 with TaxRateType = Taxable.
Else
Insert 1 row with Amount and Percentage get from Amount1 & Percentage1 with TaxRateType = EXEMPT
The example is as below table:
**DATA**
InvoiceNo | TotalAmount | Percentage1 | Amount1 | Percentage2 | Amount2
abc123 100 5 45 20 55
abc124 60 5 60 20
abc125 50 5 22 50
**MAIN**
InvoiceNo | Percentage | Amount | TaxRateType | ReferenceValue
abc123 20 55 TAXABLE 2
abc123_1 5 45 EXEMPT 1
abc124 5 60 EXEMPT 1
abc125 22 50 TAXABLE 2
I'm stuck in here for 4 hours searching for which method to use. Currently I have an idea to use if exists but still it's not correct and somehow I feel its not a good method.
IF EXISTS (SELECT ID from [alcatel].[Main_Temp] where Amount0<>'' and Amount21<>'')
BEGIN
INSERT INTO [alcatel].[Main]
( [Country],[InvoiceNo],[Amount],[Percentage],[TaxRateType],[Reference Value])
SELECT
[Country],[InvoiceNo],[Amount2],[Percentage2],'TAXABLE' as [TaxRateType],2 as [Reference Value]
FROM [alcatel].[Data];
INSERT INTO [alcatel].[Main]
( [Country],[InvoiceNo],[Amount],[Percentage],[TaxRateType],[Reference Value])
SELECT
[Country],[InvoiceNo]+'_1' as InvoiceNo,[Amount1],[Percentage1],'EXEMPT' as [TaxRateType],'1' as [Reference Value]
FROM [alcatel].[Data];
END
Followed with other condition.
I think you just want to unpivot the data with some logic:
select invoiceno + v.suffix, v.percentage, v.amount,
v.taxratetype, v.referencevalue
from data d cross apply
(values (1, d.Percentage1, d.Amount1, 'EXEMPT', ''),
(2, d.Percentage2, d.Amount2, 'TAXABLE', (case when d.amount1 is not null then '_1' else '' end))
) v(ReferenceValue, Percentage, Amount, TaxRateType, Suffix)
where amount is not null;
Here is a db<>fiddle.

SQL Group by range and total column

With the following function and stored procedure i get a resultset with 2 columns.
What i need additional is a third column total for all open invoices inner score range
It would great for any idea.
ALTER FUNCTION dbo.OpenOrders
(
#MandantId int
)
RETURNS TABLE
AS
RETURN
SELECT SUM(Invoices.Amount - ISNULL(Payment.Amount, 0)) AS Op
FROM Invoices INNER JOIN
Orders ON Invoices.OrderId = Orders.OrderId LEFT OUTER JOIN
Payment ON Invoices.InvoiceId = Payment.InvoiceId
WHERE (Orders.MandantId = #MandantId)
GROUP BY Invoice.InvoiceId, Invoices.Amount
HAVING (SUM(Invoices.Amount - ISNULL(Payment.Amount, 0)) <> 0)
ALTER PROCEDURE dbo.GetOpRanges
#MandantId int
AS
BEGIN
SELECT * INTO #tmp_ranges
FROM
//wrong in first post -> OPDebitorByMandant(#MandantId)
OpenOrders(#MandantId)
SELECT op AS [score range], COUNT(*) AS [number of occurences]
FROM
(SELECT CASE
WHEN op BETWEEN 0 AND 50 THEN ' 0- 50'
WHEN op BETWEEN 50 AND 100 THEN ' 50-100'
WHEN op BETWEEN 100 AND 500 THEN '100-500'
ELSE '500 and >' END AS op
FROM [#tmp_ranges]) AS t
GROUP BY op
RETURN
Result:
score range number of occurences range
------------------+-------------
0- 50 23
50-100 4
100-500 4
500 and > 21
What i need additional is a third column total for all open invoices inner score range.
Target result:
score range number of occurences Total
-----------+--------------------+------
0- 50 23 1.150
50-100 4 400
100-500 4 2.000
500 and > 21 22.000
Tables:
Invoices
InvoiceId CustomerId OrderId DateOfInvoice Amount
----------+----------+-------+-------------+------
1 1 20 20160301 1000.00
2 2 22 20160501 2000.00
3 1 102 20160601 3000.00
...
Orders
OrderId MandantId CustomerId DateOfOrder Amount
-------+---------+----------+-----------+-----------
20 1 1 20160101 1000.00
22 1 2 20160101 2000.00
102 1 1 20160101 3000.00
...
Payment
PaymentId MandantId CustomerId InvoiceId OrderId DateOfPayment Amount
---------+---------+----------+---------+-------+-------------+-------------
1 1 1 1 20 20160310 1000.00
2 1 2 2 22 20160505 2000.00
3 1 1 3 102 20160610 3000.00
...
hope it's helpfull and thanks again in advance for any solution

Computation with different unit of measurement

I have a table like this:-
Selling Sales
Item SIZE QTY Price U/M
---- ---- ---- ----- -----
AAA 5 10 15.00 PCE
BBB 60 5 5.50 CM
CCC 8 7 12.50 PCE
DDD 75 3 6.80 CM
I need to compute the above into this using SQL:-
Item Sales Value
AAA 150.00
BBB 1,650.00
CCC 87.50
DDD 1,530.00
The problem is the Sales U/M, some in PCE (per piece) & some in CM (per centimeter).
When it's in PCE, it shd be "Selling Price * Qty" & when it's in CM, it shd be "Selling Price * Size * Qty".
How can I do this ??
Thanks.
select item, amount = case
when salesum = 'PCE'
then price * qty
else price * size * qty
end
from ...
Use a CASE:
select item,
case um
when 'PCE' then qty * price
when 'CM' then size * qty * price
end
from your_table
where um in ('PCE', 'CM');
The where clause might be over doing it a bit but you didn't specify that um could only have those two values and I'm not sure what you want to do for an "else" clause in the case.
I would do something like this.
Select Item, Case when UM='CM' then Price * Qty else Price * Qty * Size end as Value
from sellingSales
SELECT item, qty * price AS Sales_Value
FROM your_table
WHERE um = 'PCE'
UNION ALL
SELECT item, SIZE * qty * price
FROM your_table
WHERE um = 'CM';

TVF UDF does not return the same data as SELECT

Calling the UDF like so:
SELECT
product_name,
SUM(quantity) AS SumQty,
SUM(face_value) AS SumFaceValue,
SUM(net_cost)AS SumNetCost,
SUM(face_value - net_cost) AS SumScripRebate,
organization_name
FROM getSalesSummary(#GLSCOrgId, #BeginDate, #EndDate) getSalesSummary
GROUP BY product_name, organization_name
ORDER BY product_name
yields:
"Chili's 1 25.00 22.75 2.25 Sample Organization 1
CVS/pharmacy 1 25.00 23.50 1.50 Sample Organization 1
Macy's 1 100.00 90.00 10.00 Sample Organization 1"
Using the UDF logic and testing the results with SELECT:
SELECT
product_name,
SUM(quantity) AS SumQty,
SUM(face_value) AS SumFaceValue,
SUM(net_cost) AS SumNetCost,
SUM(face_value - net_cost) AS SumScripRebate,
organization_name
FROM #ReturnTable
GROUP BY product_name, organization_name
ORDER BY product_name
yields:
"Chili's 4 100.00 91.00 9.00 Sample Organization 1
CVS/pharmacy 1 25.00 23.50 1.50 Sample Organization 1
Macy's 1 100.00 90.00 10.00 Sample Organization 1"
#ReturnTable is the table returned by the UDF and is created like so:
INSERT INTO #ReturnTable(product_name,
unit_price,
quantity,
face_value,
net_cost,
organization_name)
(select * from #TablePartial UNION select * from #TableClosed)
The test with the SELECT and variables is returning the correct data, but calling the UDF is not getting those other 3 Chili's records. I am using the same data for parameters. I'm quite new to UDFs and I'm not sure why it would return different data than what the SELECT does. Any suggestions and/or answers?
You probably need UNION ALL not UNION
Looking at the two result sets it adds up as though the 4 Chilli's rows are all the same.
Chili's 1 25.00 22.75 2.25 Sample Organization 1
Chili's 1 25.00 22.75 2.25 Sample Organization 1
Chili's 1 25.00 22.75 2.25 Sample Organization 1
Chili's 1 25.00 22.75 2.25 Sample Organization 1
-------------------------------------------------------------
Chili's 4 100.00 91.00 9.00 Sample Organization 1
Using UNION will remove the duplicates leaving you with one row.
The only thing I can think of is the UNION change it to UNION ALL UNION will eliminate dups
Run these queries to see the difference
select 1 as a
union
select 1
union
select 1
select 1 as a
union all
select 1
union all
select 1