Multiple SELECT Statement using One Table of SQL - sql

Hope u all fine.
Actually I'm working on a Project and need to calculate daily TOTAL_SALE and TOTAL_CASH and TOTAL_CREDIT ....
Following is my Query but my Query Gives Overall SUM of Payments in TOTAL_CASH and in TOTAL_CREDIT as it has to be like this ..
+------------+------------+--------------+
| TOTAL_SALE | TOTAL_CASH | TOTAL_CREDIT |
+------------+------------+--------------+
| 1000 | 250 | 750 |
+------------+------------+--------------+
Following is my SQL Query :-
SELECT
sss.creation_date , SUM(sss.payment_due) as 'Total Sale',
(SELECT SUM(s.payment_due) FROM sale s WHERE s.payment_method LIKE '%Cash_%' AND s.shop='10'
AND s.DateNum >='20181201000000' AND s.DateNum <='20181231235959' GROUP BY s.creation_date)as 'Total Cash' ,
(SELECT SUM(ss.payment_due) FROM sale ss WHERE ss.payment_method LIKE '%cCredit_%' AND ss.shop='10'
AND ss.DateNum >='20181201000000' AND ss.DateNum <='20181231235959' GROUP BY ss.creation_date)as 'Total Credit' ,
SUM(discount) as 'Total Discount' , SUM(number_of_item_purchased) as 'Total Sold'
FROM Sale sss
WHERE sss.shop='10' AND sss.DateNum >='20181201000000' AND sss.DateNum <='20181231235959'
GROUP BY sss.creation_date

You can try below using conditional aggregation
SELECT
SUM(payment_due) as 'Total Sale',
SUM(case when payment_method LIKE '%Cash_%' then s.payment_due end) as 'Total Cash' ,
SUM(case when payment_method LIKE '%cCredit_%' then payment_due end) as 'Total Credit',
SUM(discount) as 'Total Discount' ,
SUM(number_of_item_purchased) as 'Total Sold'
FROM Sale
WHERE shop='10' AND DateNum >='20181201000000' AND DateNum <='20181231235959'

Related

SQL How to group data into separate month columns

So I'm running this query to get the name of the customer, total amount ordered, and number of orders they've submitted. With this query, I get their entire history from March to July, what I want is the name, march amount total/# of orders, april amount total/# of orders, may amount total/# of orders, ..... etc.
SELECT customer_name,MONTH(created_on), SUM(amount), COUNT(order_id)
FROM customer_orders
WHERE created_on BETWEEN '2020-03-01' AND '2020-08-01'
GROUP BY customer_name, MONTH(created_on)
If you want the values in separate columns, then use conditional aggregation:
SELECT customer_name,
SUM(CASE WHEN MONTH(created_on) = 3 THEN amount END) as march_amount,
SUM(CASE WHEN MONTH(created_on) = 3 THEN 1 ELSE 0 END) as march_count,
SUM(CASE WHEN MONTH(created_on) = 4 THEN amount END) as april_amount,
SUM(CASE WHEN MONTH(created_on) = 4 THEN 1 ELSE 0 END) as april_count,
. . .
FROM customer_orders
WHERE created_on >= '2020-03-01' AND
created_on < '2020-08-01'
GROUP BY customer_name;
Notice that I changed the date filter so it does not include 2020-08-01.

T-SQL: Rows to Columns

I am a SQL beginner, so can anyone please help me with this?
I have a table like this
YearMonth | Customer | Currency | BusinessType | Amount
04-2020 | 123 | EUR | Budget | 500
04-2020 | 123 | EUR | Forecast | 300
04-2020 | 123 | EUR | Sales | 700
And now I need it like:
YearMonth | Customer | Currency | Amount Budget | Amount Forecast | Amount Sales
04-2020 | 123 | EUR | 500 | 300 | 700
Is something like this possible?
Thanks in advance for your help!
Use conditional aggregation:
select yearmonth, customer, currency,
sum(case when businesstype = 'Budget' then amount end) as budget,
sum(case when businesstype = 'Forecast' then amount end) as forecast,
sum(case when businesstype = 'Sales' then amount end) as sales
from t
group by yearmonth, customer, currency;
You can do aggregation :
select yearmonth, customer, currency,
sum(case when businesstype = 'budget' then amount else 0 end),
sum(case when businesstype = 'Forecast' then amount else 0 end),
sum(case when businesstype = 'Sales' then amount else 0 end)
from table t
group by yearmonth, customer, currency;
Also, you may want to add an "Other" to capture any new Business Types:
select yearmonth, customer, currency,
sum(case when businesstype = 'Budget' then amount end) as budget,
sum(case when businesstype = 'Forecast' then amount end) as forecast,
sum(case when businesstype = 'Sales' then amount end) as sales,
sum(case when businesstype not in ('Budget', 'Forecast', 'Sales') then amount end) as other
from t
group by yearmonth, customer, currency;
This type of requirements are usually resolved using T-SQL PIVOT relational operation (https://learn.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-ver15). For the above example I used the following query to achieve this:
-- Create a temporary table to store the data.
IF (OBJECT_ID('tempdb..##temp2') IS NOT NULL) DROP TABLE ##temp2
CREATE TABLE ##temp2 (Id int IDENTITY (1,1) PRIMARY KEY, YearMonth varchar(100), Customer int, Currency varchar(100), BusinessType varchar(100), Amount int)
INSERT ##temp2
VALUES
('04-2020', 123,'EUR','Sales', 700),
('04-2020', 123,'EUR','Budget', 500),
('04-2020', 123,'EUR','Forecast', 300)
-- Using PIVOT allows you to move rows into columns
SELECT pivot_table.YearMonth,
pivot_table.Customer,
pivot_table.Currency,
[Amount Forecast] = pivot_table.Forecast,
[Amount Budget] = pivot_table.Budget,
[Amount Sales] = pivot_table.Sales
FROM
(
SELECT YearMonth,
Customer,
Currency,
BusinessType,
Amount
FROM ##temp2
) t
PIVOT
(
SUM(Amount)
FOR BusinessType IN ([Sales], [Budget], [Forecast])
) AS pivot_table;

SQL query to calculate totals

I'm quite new to SQL querying so please go easy on me if what I've done so far is really odd :)
I have two tables - A for Income and B for Expenditure:
Business_ID Income_Desc Income_Amount
1 Income A 1000
1 Income B 3000
1 Income C 2000
Business_ID Expen_Amount
1 2500
I'd like to produce a table that shows each of the income amounts, the one expenditure amount, the total income, the total expenditure and a Grand Total of total income-total expenditure.
Something like this if possible
Business_ID Income Description Income Amount Expenditure Amount Total
1 Income A 1000 2500 -
1 Income B 3000 - -
1 Income C 2000 - -
1 All Amounts 6000 2500 3500
This is what I've tried so far
SELECT a. Business_ID, COALESCE (a.Income_Desc, 'All Amounts') AS 'Income Description', SUM(a.Income_Amount) AS 'Income Amount', SUM(b.Expen_Amount) AS Expenditure Amount', (sum(a.Income_Amount)-SUM(b.Expen_Amount)) AS 'Total'
FROM Income AS a LEFT JOIN Expenditure AS b ON a.Business_ID = b. Business_ID
GROUP BY a. Business_ID, a.Income_Desc WITH ROLLUP
The result I'm getting is this
Business_ID Income Description Income Amount Expenditure Amount Total
1 Income A 1000 2500 -1500
1 Income B 3000 2500 500
1 Income C 2000 2500 -500
1 All Amounts 6000 7500 -1500
All Amounts 6000 7500 -1500
Is it possible to get an output like the one I provided above? Could you show me how to achieve it (or something very close) please?
Thanks
You can use row_number() for the join:
with ie as (
select i.business_id, i.income_desc, i.income_amount,
e.expen_amount
from (select i.*,
row_number() over (partition by business_id order by income_desc) as seqnum
from income i
) i left join
(select e.*,
row_number() over (partition by business_id order by expen_amount) as seqnum
from expenditure e
) e
on i.business_id = e.business_id and i.seqnum = e.seqnum
)
select ie.*
from ie
union all
select business_id, 'Total', sum(income_amount), sum(expen_amount)
from ie
group by business_id;
You could make a sub query out of your original query and only select values where the business ID is not null. Furthermore, use CASE WHEN to identify those values < 0 and replace it with "-":
SELECT x.Business_ID
, x.`Income Description`
, x.`Income Amount`
, x.`Expenditure Amount`
, x.Total
FROM
(SELECT a. Business_ID
, COALESCE (a.Income_Desc, 'All Amounts') AS 'Income Description'
, SUM(a.Income_Amount) AS 'Income Amount'
, SUM(b.Expen_Amount) AS 'Expenditure Amount'
, CASE WHEN (sum(a.Income_Amount)-SUM(b.Expen_Amount)) < 0
THEN '-'
ELSE (sum(a.Income_Amount)-SUM(b.Expen_Amount))
END AS 'Total'
FROM Income AS a
LEFT JOIN Expenditure AS b ON a.Business_ID = b.Business_ID
WHERE a.Business_ID is not null and b.Business_ID is not null
GROUP BY a.Business_ID, a.Income_Desc WITH ROLLUP) as x
where x.Business_ID is not null
DB Fiddle

Monthly sales as column

SQL question, making monthly and yearly sales as column:
I have two tables:
t_items (item_num, item_name, itm_qnt)
t_items_dtl (item_num, invdate, itm_qnt_out, itm_qnt_in)
Columns are:
itm_qnt = current stock
invdate = invoice date
item_qnt_out = number of sold specific item in the invoice
item_qnt_in = number of returned specific item in the invoice
I want to get the following columns:
item_num | item_name | currnt_stock | QTY sold 2018 | QTY sold:Jan2018 | Feb 2018 | March 2018 .... Dec 2018
For now I used this query but it gives me only the total sales of each item:
SELECT
i.item_num AS ItemNum,
i.item_name AS ItemName,
sum(d.itm_qnt_out-d.itm_qnt_in) AS QTOUT,
i.itm_qnt AS Stock
FROM
dbo.t_items AS i
FULL OUTER JOIN
t_items_dtl AS d ON i.item_num = d.item_num
GROUP BY
i.item_num, i.item_name, i.itm_qnt;
How can I add monthly and yearly sales by column (not rows)?
Depending on the database you are using there may be more elegant ways to get year and month from a date but bottom-line, you probably want something like:
SELECT
i.item_num AS ItemNum,
i.item_name AS ItemName,
sum(d.itm_qnt_out-d.itm_qnt_in) AS QTOUT,
sum(CASE WHEN to_char(invdate,'mm') = '01' THEN d.itm_qnt_out-d.itm_qnt_in ELSE 0 END) AS QTOUTJan,
sum(CASE WHEN to_char(invdate,'mm') = '02' THEN d.itm_qnt_out-d.itm_qnt_in ELSE 0 END) AS QTOUTFeb,
sum(CASE WHEN to_char(invdate,'mm') = '03' THEN d.itm_qnt_out-d.itm_qnt_in ELSE 0 END) AS QTOUTMar,
/*Repeat for every month*/
i.itm_qnt AS Stock
FROM
dbo.t_items AS i
FULL OUTER JOIN
t_items_dtl AS d ON i.item_num = d.item_num
WHERE to_char(invdate, 'yyyy') = '2018'
GROUP BY
i.item_num, i.item_name, i.itm_qnt;
Compared to your code, I have defined a column for each month + added a WHERE to filter the entire thing to 2018.

Grouping PostgreSQL Running Total Results

I am trying to get a running total for 2 stores. The query that I have gets the running total for both stores together. How can I change the query to get the running total for each store separately? Below is my query. The database can be found here.
select store_id,amount, sum(amount) over (order by rental_date)
from payment
join rental on payment.rental_id=rental.rental_id
join store on payment.customer_id=store.store_id
This is the result that I get:
store id amont sum
1 5.99 5.99
1 0.99 6.98
1 9.99 16.97
1 4.99 21.96
2 2.99 24.95
1 4.99 29.94
1 0.99 30.93
1 3.99 34.92
Use partition by store_id in
sum(amount) over (partition by store_id order by store_id, rental_date)
if you want them in different columns you do it like this
select
store_id,
amount,
sum(case when store_id = 1 then amount else 0 end) over (order by rental_date) as store1_sum,
sum(case when store_id = 2 then amount else 0 end) over (order by rental_date) as store2_sum,
from payment
join rental on payment.rental_id=rental.rental_id
join store on payment.customer_id=store.store_id
for different rows you can partition as #BarbarosĂ–zhan