Is this possible to do in a single query?
I have a sales table that I want to query. The table has details of our sales transactions at the item level, so each record contains fields like: cust_no, item_no, amount, month, year.
I want to summarize the sales info by customer by month by year. I know I can summarize the data like this:
select cust_no,
fiscal_year,
month,
sum(amount) as totalAmt,
group by cust_no, month, fiscal_year
...to get something like this:
cust_no
month
fiscal year
totalAmt
cust_123
1
2022
123.45
cust_345
1
2022
456.78
But I'd like to split out the sales amount depending on whether or not the item_no field is empty or not (because "products" have an item_no where as "services" have a blank item_no).
This is the result I'm going for:
cust_no
month
fiscal year
totalAmt where item_no != ''
totalAmt where item_no = ''
cust_123
1
2022
123.45
222.22
cust_345
1
2022
456.78
111.11
Is there a way to do this in a single query?
May be you can try following query.
select
cust_no,
fiscal_year,
month,
SUM(CASE WHEN item_no is NOT NULL THEN totalAmt ELSE 0 END) as total_amt_when_non_null,
SUM(CASE WHEN item_no is NULL THEN totalAmt ELSE 0 END) as total_amt_when_null
FROM table
group by cust_no, month, fiscal_year
Related
I'm trying to do a SQL query to give the cash transactions by day with a sum of the total cash balance grouped by Company and Department. I can get each query to work separately, but can't figure out how to nest the summary query as a subquery successfully. Below are the two queries that work. I thought I could do a temporary table, but have not been able to get that to work either (get error message that token "temporary" , "private temporary" invalid with Oracle DB) and most of the information I've researched says you can do the same thing with a subquery. I'd prefer to do a subquery anyway if it's possible.
#sum of YTD cash balance
Select Company, department, sum(amount) as Balance
From GL_Table
Where Company in ('A','B','C') and FY = 21 and account = 'cash' and date between 1/1/2021 and 1/31/2021
Group By Company, department
#transactions by day
Select Company, Department, date, Amount
From GL_Table
Where Company in ('A','B','C') and FY = 21 and and account = 'cash' and date = 1/1/2021-1/31/2021
Group By Company, department, date
You can GROUP BY date and the correct date that corresponds to the most recent transaction via sub query.
SELECT Company, department, sum(amount) FROM (
SELECT MAX(date), Company, department, amount FROM GL_TABLE GROUP BY date
) WHERE
Company in ('A','B','C') and FY = 21 and account = 'cash' and date between
1/1/2021 and 1/31/2021
GROUP BY
Company, department, date
also check out: SQL: Select most recent date for each category
I'm trying to get the quarter on quarter revenue growth for only the current quarter from a dataset. I currently have a query that looks something like this
Select
x.Year,
x.quarter,
x.product,
x.company_id,
y.company,
SUM(x.revenue)
FROM
company_directory y
LEFT JOIN (
SELECT
DATEPART(YEAR, #date) year,
DATEPART(QUARTER, #date) quarter,
product,
SUM(revenue)
FROM sales
WHERE year => 2018 ) x
ON y.company_id = x.company_id
The data I get is in this format
Year Quarter Product company_id company revenue
2020 Q2 Banana 1092 companyX $100
What I'm trying to do is get quarter on quarter growth for revenue if it's reporting the current quarter. So for example, in the above data, because we're in Q2-2020, I want an extra column to say QoQ is x% which will compare Q2 vs Q1 revenue. If the row is reporting Q1-2020 or Q2-2019 QoQ will be empty because neither of those are the current quarter based on today's date.
Expected result
Year Quarter Product company_id company revenue QoQ
2020 Q2 Banana 1092 companyX $100 20%
2020 Q1 Pear 1002 companyX $23 NULL
I'm not entirely sure how to go about this, haven't had much luck searching. Any idea how I can implement?
You can use window functions.
select
s.yr,
s.qt,
s.product,
s.company_id,
cd.company,
s.revenue,
1.0 * (
s.revenue
- lag(s.revenue) over(partition by s.product, s.company_id order by s.yr, s.qt)
) / lag(s.revenue) over(partition by s.product, s.company_id order by s.yr, s.qt) as QoQ
from company_directory cd
inner join (
select
datepart(year, sales_date) yr,
datepart(quarter, sales_date) qt,
product,
company_id,
sum(revenue) revenue
from sales
where sales_date >= '2018-01-01'
group by
datepart(year, sales_date) year,
datepart(quarter, sales_date) quarter,
product,
company_id
) s on s.company_id = cd.company_id
Notes:
your code is not valid MySQL; I assume that you are running SQL Server instead of MySQL
the use of a variable in the subquery does not make sense - I assume that you have a column called sales_date in table sales that holds the sales date
your group by clauses are inconsistent with your select clauses - I assume that you want the quarter to quarter sales growth per company and per product
you might need to ajust the QoQ computation to your actual definition of the quarter to quarter growth
I don't see the point for a left join, so I used inner join instead
You need analytical window function LAG
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=40a7ba897df766f913ebd99e2f2a0f4e
I have a table with columns:
customer_id,
customer_name,
transaction_number,
transaction_date,
transaction_type,
transaction_value,
transaction_approved.
I am trying to generate a list where the columns are
customer_id,
customer_name,
total transaction value
where the transaction_type is credit and made in 2020, total transaction value where the transaction_type is debit or cash in 2019.
However, this list is only including the customer_id who made at least one transaction using credit in the year 2020. Basically, how would I use the where clause to get the criteria for the customer_id and then get the rest of the list based on those customer_ids only?
It would be returning
the customer_id where the at least one transaction was made using credit in the year 2019
and then the other columns next to it would return the values for that customer_id
Something like that should do the trick:
select customer_id, customer_name, sum(effective_value)
from (
select customer_id, customer_name,
case
when transaction_type in ('debit', 'cash')
and '2019' <= transaction_date
and transaction_date < '2020'
then transaction_value
else 0
END effective_value
from transactions as T
) as T
group by customer_id, customer_name;
You'll have to adapt the transaction_date comparision to meet your database syntax.
What I understand from above description, user needs customers which has transaction_type credit in 2020, but he wants sum of amount for year 2019 and that also for transaction type debit and cash . Please update question if its not the case
select
customer_id, customer_name,
sum(coalesce(transaction_value,0)) as total_transaction_value
from
table_T
where
customer_id in (select distinct customer_id from table_T
where transaction_type = 'credit'
and transaction_date >= '2020-01-01')
and transaction_date >= '2019-01-01'
and transaction_date < '2020-01-01'
and transaction_type in ('debit', 'cash')
group by
customer_id, customer_name
Database is not mentioned you may have to parse date field accordingly
I have a table with columns order_id, customer_id, order_date and Amount.
How to find the customers who have ordered at least 2 times each month of the year in SQL (from Jan to Dec)?
I think you are looking for something like this
select
order_date_year,
customer_id
from
(
select
year(order_date) as order_date_year,
month(order_date) as order_date_month,
customer_id,
count(*) as number_of_orders
from
tableName
group by
year(order_date),
month(order_date),
customer_id
having
count(*) >= 2
) as t
group by
order_date_year,
customer_id
having
count(*) = 12
I have table like this
PartID Quantity Date
12315 1 2017-01-24
51245 3 2017-01-26
12345 4 2017-02-20
12415 1 2017-02-25
..... .. ...........
I need for the report result like:
Monthly Quantity January: 4
Monthly Quantity February: 5
So in my report - every column should have the name of month and include all quantities (count) for this month. Any help would be appreciated.
I think you are looking for a query like:
select month(Date), sum(Quantity)
from table
group by month(Date)
In MS SQL :
You can use something like this:
DATENAME() function returns a specified part of a given date, as a string value.
To know more about DATENAME(), please visit https://www.w3schools.com/sql/func_sqlserver_datename.asp
CAST() function converts an expression from one data type to another data type.
To know more about CAST(), please visit https://www.w3schools.com/sql/func_sqlserver_cast.asp
SELECT
MONTH(Date) AS MonthNo,
'Monthly Quantity ' + DATENAME(MONTH, date) + ' : ' + CAST(SUM(Quantity) AS nvarchar(10)) AS Monthwise
FROM parttable
GROUP BY DATENAME(MONTH, date),
MONTH(Date)
ORDER BY MONTH(Date)
So the output will be
Two options you can have :
1) create another column and store name of month in it .
PartID Quantity Date. Month
12315 1 2017-01-24. January
51245 3 2017-01-26. January
12345 4 2017-02-20. February
12415 1 2017-02-25. February
And use below query to get the report as you needed :
Select sum(Quantity) as total_quantity, Month from table group by Month
2) by using inbuilt date and time functions of MySQL.
Select sum(Quantity) as total_quantity, Month(Date) as month from table group by Month(Date)
Which database are you using?
On SQL Server:
SELECT
DATENAME(month, Date) AS 'Month Name', SUM(Quantity)
FROM table
GROUP BY DATENAME(month, Date)