how can i set the alias of column`s sum value based on another column in same table in sql? - 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

Related

sum a value that appears on multiple rows ones per id in microsoft sql

I have a table that looks like below. In my query I'm sum:ing the order item value for each order item type, but I'm not sure how to summarize the providerfee per order id when the providerfee appears on multiple rows. Sum(providerfee) would give me 60 instead of 30.
Raw table (sample):
order id
order item type
order item value
providerfee
1
Product
300
30
1
Shipping
40
30
1
Invoicefee
30
30
Aggregated table if I would query above example table with the query I'm using now:
noOfOrders
productAmount
ShippingAmount
InvoiceAmount
providerfee
1
300
40
30
60
What value I wish to get in the providerfee column in my aggregated table instead:
noOfOrders
productAmount
ShippingAmount
InvoiceAmount
providerfee
1
300
40
30
30
Does anyone now best practice of fetching the right sum per order id from the providerfee-column? I think it won't make any sense to publish the actual query I'm writing but basically what I'm doing to fetch the amounts for order item types is:
with amounts as (
select
case when orderItemType= 'Product' then orderItemValue else 0 end as productAmount
,case when orderItemType = 'Shipping' then orderItemvalue else 0 end as shippingAmount
case when orderItemType = 'Fee' then orderItemvalue else 0 end as InvoicefeeAmount
,providerfee
from exampleTable
)
select
sum(amounts.productAmount) as productAmount
,sum(amounts.shippingAmount) as shippingAmount
,sum(amounts.invoicefeeAmount) as invoicefeeAmount
,sum(amounts.providerfee) as providerfeeAmount <---- This one gives me too high values since I'm summing every rows and providerfee appears on every row
from amounts
Here's a picture of how my actual table look like. Providerfee is supposed to be 638 just like invoiceAmount
One thing I also tried was a logic with row number function. But this gave me a result where three providerfees where missing. Instead of 638 I got 551. Can't see why since I counted in the raw table and got it to 638 myself. Not sure if I'm missing something logical with row number function that can have an impact on the SUM. Should I try another function to be able to pull out only one providerfee-row per order id?
with amounts as (
select
row_number() over (partition by orderId order by orderItemTimestamp DESC) as rn
,case when orderItemType= 'Product' then orderItemValue else 0 end as productAmount
,case when orderItemType = 'Shipping' then orderItemvalue else 0 end as shippingAmount
,case when orderItemType = 'Fee' then orderItemvalue else 0 end as InvoicefeeAmount
,providerfee
from exampleTable
)
select
sum(amounts.productAmount) as productAmount
,sum(amounts.shippingAmount) as shippingAmount
,sum(amounts.invoicefeeAmount) as invoicefeeAmount
,sum(amounts.providerfee) as providerfeeAmount <---- This one gives me too high values since I'm summing every rows and providerfee appears on every row
,sum(case when (amounts.providerfee is not null and amounts.rn = 1) then amounts.providerfee else 0 end) as providerfee2
from amounts
Grand total can be done using conditional aggregation. (Note that I here expect every Orderto have exactly one Invoicefee.)
select COUNT(distinct OrderId) as noOfOrders,
SUM(case when orderItemType = 'Product' then orderItemValue else 0 end) as productAmount,
SUM(case when orderItemType = 'Shipping' then orderItemvalue else 0 end) as shippingAmount,
SUM(case when orderItemType = 'Fee' then orderItemvalue else 0 end) as InvoicefeeAmount,
SUM(case when orderItemType = 'Fee' then providerfee else 0 end) as providerfee
from amounts
You can also add a GROUP BY, to get aggregation per order:
select OrderId,
SUM(case when orderItemType = 'Product' then orderItemValue else 0 end) as productAmount,
SUM(case when orderItemType = 'Shipping' then orderItemvalue else 0 end) as shippingAmount,
SUM(case when orderItemType = 'Fee' then orderItemvalue else 0 end) as InvoicefeeAmount,
SUM(case when orderItemType = 'Fee' then providerfee else 0 end) as providerfee
from amounts
group by OrderId

how to sum all columns with same id

Hi i have the following results:
i need to sum up all the items that have cashamount and same Payment code = 9
i have tried this query:
SELECT
CASE
WHEN StoreID = 1 THEN 'CWM'
WHEN StoreID = 2 THEN 'CWD' END as accountcode,
DocEntry,
PaymentCode,
case when PaymentCode <> 1 then paymentamount end as OtherPaymentAmount,
sum(case when PaymentCode = 1 then paymentamount end) as CashAmount,
tenders.sapcreditcard AS sapcreditcard,
--paymentamount,
-- sum (case when PaymentCode >= 1 then paymentamount else NULL end) as Total,
FileName, BPA_ProcessStatus, ERP_PaymentProcessed
FROM [Plu].[dbo].[payments_header] LEFT JOIN tenders ON payments_header.PaymentCode = tenders.postenderid
WHERE BPA_ProcessStatus='N' and ERP_PaymentProcessed='N'
group by PaymentCode, paymentamount, docentry, storeid,sapcreditcard, FileName, BPA_ProcessStatus,ERP_PaymentProcessed, cashamount
what im missing?
The GROUP BY clause lists all the columns you want to use to create separate groups. Yours is as follows...
GROUP BY
PaymentCode,
paymentamount,
docentry,
storeid,
sapcreditcard,
FileName,
BPA_ProcessStatus,
ERP_PaymentProcessed,
cashamount
Any time any of these are different, you'll get a separate row.
This means that your sum(case when PaymentCode = 1 then paymentamount end) ends up making very little sense.
Your GROUP BY says you want each different payment amount on a different row
Your SELECT says you want to aggregate multiple paymounts amounts
My best guess is that you want this...
SELECT
CASE
WHEN StoreID = 1 THEN 'CWM'
WHEN StoreID = 2 THEN 'CWD'
END
AS accountcode,
DocEntry,
PaymentCode,
SUM(CASE WHEN PaymentCode <> 1 THEN paymentamount END) AS OtherPaymentAmount,
SUM(CASE WHEN PaymentCode = 1 THEN paymentamount END) AS CashAmount,
tenders.sapcreditcard,
FileName,
BPA_ProcessStatus,
ERP_PaymentProcessed
FROM
[Plu].[dbo].[payments_header]
LEFT JOIN
tenders
ON payments_header.PaymentCode = tenders.postenderid
WHERE
BPA_ProcessStatus='N'
AND ERP_PaymentProcessed='N'
GROUP BY
CASE
WHEN StoreID = 1 THEN 'CWM'
WHEN StoreID = 2 THEN 'CWD'
END,
DocEntry,
PaymentCode,
tenders.sapcreditcard,
FileName,
BPA_ProcessStatus,
ERP_PaymentProcessed
Added SUM() around the OtherPaymentAmount calculations, to match CashAmount
Changed the GROUP BY to match the non-aggregated columns in the SELECT
NOTE: In all the places where you specify a column name, your should always qualify it with the source table's name.

tsql - pivot sum of employee

I have here a sample table data which i want to use pivot and make my DedCode data into column.
the AMount example is already computed to its total but how can i count the number of employee if it is same with branch,deptcode and emptype.
my sample table data.
expected output:
You can use conditional aggregation:
select branch, deptcode, emptype, sum(empcount) as empcount,
sum(case when dedcode = 'PHIC' then amount else 0 end) as phic,
sum(case when dedcode = 'SLOAN' then amount else 0 end) as sloan,
sum(case when dedcode = 'VLOAN' then amount else 0 end) as vloan
from t
group by branch, deptcode, emptype;

SQL select grouping and subtract

i have table named source table with data like this :
And i want to do query that subtract row with status plus and minus to be like this group by product name :
How to do that in SQL query? thanks!
Group by the product and then use a conditional SUM()
select product,
sum(case when status = 'plus' then total else 0 end) -
sum(case when status = 'minus' then total else 0 end) as total,
sum(case when status = 'plus' then amount else 0 end) -
sum(case when status = 'minus' then amount else 0 end) as amount
from your_table
group by product
There is another method using join, which works for the particular data you have provided (which has one "plus" and one "minus" row per product):
select tplus.product, (tplus.total - tminus.total) as total,
(tplus.amount - tminus.amount) as amount
from t tplus join
t tminus
on tplus.product = tminus.product and
tplus.status = 'plus' and
tplus.status = 'minus';
Both this and the aggregation query work well for the data you have provided. In other words, there are multiple ways to solve this problem (each has its strengths).
you can query as below:
select product , sum (case when [status] = 'minus' then -Total else Total end) as Total
, sum (case when [status] = 'minus' then -Amount else Amount end) as SumAmount
from yourproduct
group by product

Divide and sum in 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