how to sum all columns with same id - sql

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.

Related

How to exclude 0 from count()? in sql?

I have a code as below where I want to count number of first purchases for a given period of time. I have a column in my sales table where if the buyer is not a first time buyer, then is_first_purchase = 0
For example:
buyer_id = 456391 is already an existing buyer who made purchases on 2 different dates.
Hence is_first_purchase column will show as 0 as per below.
If i do a count() on is_first_purchase for this buyer_id = 456391 then it should return 0 instead of 2.
My query is as follows:
with first_purchases as
(select *,
case when is_first_purchase = 1 then 'Yes' else 'No' end as first_purchase
from sales)
select
count(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
from first_purchases
where buyer_id = 456391
and date_id between '2021-02-01' and '2021-03-01'
order by 1 desc;
It returned the below which is not an intended output
Appreciate if someone can help explain how to exclude is_first_purchase = 0 from the count, thanks.
Because COUNT function count when the value isn't NULL (include 0), if you don't want to count, need to let CASE WHEN return NULL
There are two ways you can count as your expectation, one is SUM other is COUNT but remove the part of else 0
SUM(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
COUNT(case when first_purchase = 'Yes' then 1 end) as no_of_first_purchases
From your question, I would combine CTE and main query as below
select
COUNT(case when is_first_purchase = 1 then 1 end) as no_of_first_purchases
from sales
where buyer_id = 456391
and date_id between '2021-02-01' and '2021-03-01'
order by 1 desc;
I think that you are using COUNT() when you want SUM().
with first_purchases as
(select *,
case when is_first_purchase = 1 then 'Yes' else 'No' end as first_purchase
from sales)
select
SUM(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
from first_purchases
where buyer_id = 456391
and date_id between '2021-02-01' and '2021-03-01'
order by 1 desc;
You could simplify your query as:
SELECT COUNT(*) AS
FROM sales no_of_first_purchases
WHERE is_first_purchase = 1
AND buyer_id = 456391
AND date_id BETWEEN '2021-02-01' AND '2021-03-01'
ORDER BY 1 DESC;
It is better to avoid the use of functions like IF and CASE when it can be done with WHERE.
The simplest approach for Trino (f.k.a. Presto SQL) is to use an aggregate with a filter:
count(name) FILTER (WHERE first_purchase = 'Yes') AS no_of_first_purchases

SQL - separate results of same column into different cloumns using multiple where statements

I have no prior SQL knowledge. I am trying to get sum of all debitTransactions for different transactionType for each FolioNumber
I have the following code but it gives sum of all the debit transactions for each transaction type for each folio.
But all I want is sum of all gst(106) for each folio in one column, sum of all levy(105) for each folio in second column and sum of all roomRevenue(100) for each folio in third column.
---non working code
SELECT FolioNumber,
(Select SUM(debitTransactions) FROM HISTTRN WHERE transactionType = 106) as gst,
(Select SUM(debitTransactions) FROM HISTTRN WHERE transactionType = 105) as levy,
(Select SUM(debitTransactions) FROM HISTTRN WHERE transactionType = 100) as roomRevenue
FROM
HISTTRN
GROUP BY FolioNumber
ORDER BY FolioNumber
Following code does work if I only want one transactionType but I want 3 different transaction types
---working code
SELECT FolioNumber,
SUM(debitTransactions) as gst
FROM HISTTRN
WHERE transactionType = 106
GROUP BY FolioNumber
ORDER BY FolioNumber
Is there a possible way of doing that? Thanks
SELECT FolioNumber,
SUM(case when transactionType = 106 then debitTransactions else 0 end) as gst,
SUM(case when transactionType = 105 then debitTransactions else 0 end) as levy,
SUM(case when transactionType = 100 then debitTransactions else 0 end) as roomRevenue
FROM HISTTRN
GROUP BY FolioNumber
ORDER BY FolioNumber

BigQuery: group counters by month after self-join

I have table that looks like this:
I'm trying to build a query, that will show specific partnerId counters groupped by keywordName and month.
To solve first part(without grouping by month), I've built this query:
SELECT keywordName, COUNT(keywordName) as total, IFNULL(b.ebay_count, 0) as ebay, IFNULL(c.amazon_count, 0) as amazon,
FROM LogFilesv2_Dataset.FR_Clickstats_v2 a
LEFT JOIN
(SELECT keywordName as kw , SUM(CASE WHEN partnerId='eBay' THEN 1 ELSE 0 END) as ebay_count
FROM LogFilesv2_Dataset.FR_Clickstats_v2
WHERE partnerId = 'eBay' GROUP BY kw) b
ON keywordName = b.kw
LEFT JOIN
(SELECT keywordName as kw , SUM(CASE WHEN partnerId='AmazonApi' THEN 1 ELSE 0 END) as amazon_count
FROM LogFilesv2_Dataset.FR_Clickstats_v2
WHERE partnerId = 'AmazonApi' GROUP BY kw) c
ON keywordName = c.kw
WHERE keywordName = 'flipper' -- just to filter out single kw.
GROUP BY keywordName, ebay, amazon
It works quite well and returns following output:
Now I'm trying to make additional group by month, but all my attempts returned incorrect results.
Final output supposed to be similar to this:
You can do this with conditional aggregation:
select
date_trunc(dt, month) dt,
keywordName,
count(*) total,
sum(case when partnerId = 'eBay' then 1 else 0 end) ebay,
sum(case when partnerId = 'AmazonApi' then 1 else 0 end) amazon
from LogFilesv2_Dataset.FR_Clickstats_v2
group by date_trun(dt, month), keywordName

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

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