Complicated Sql Query Of Joining Two Tables - sql

I having Following Two Tables and wants the result date and bank wise. The Example is as below.
Table1: Name:- AccountMast
companyID A/CID Name BalDR BalCR
102 14 SHOBHA NULL NULL
102 15 SONKI NULL NULL
102 16 BANK OF INDIA null 12000
Table2 Name :- DeBank
companyID transID date name particulars deposit withdrawal
102 2 12/04/2012 BANK OF INDIA MAHENDRA 1000 NULL
102 4 15/04/2012 CENTRAL BANK MAHENDRA 1000 NULL
102 3 20/05/2012 BANK OF INDIA MAHENDRA 2000 NULL
Result
BANK WISE RESULT BANK OF INDIA
date transID particulars deposit withdrawal BALANCE
01/04/2012 BAL B/F 12000
12/04/2012 2 MAHENDRA 1000 NULL 13000
20/05/2012 3 MAHENDRA 2000 NULL 15000
BANK WISE RESULT CENTRAL BANK OF INDIA
date transID particulars deposit withdrawal BALANCE**
01/04/2012 BAL B/F
15/04/2012 4 MAHENDRA 2000 NULL 2000
So what is the sql statement for it?.

Related

SQL query to select specific fields, process sum and count from two tables

i have these two tables
ORDERS
id order_id e_id e_name
1 1000 1001 Tom
2 1009 1001 Tom
3 1010 1001 Tom
4 1011 1002 Parker
5 1012 1002 Parker
6 1013 1003 Rohan
Transactions
id order_id amount status
1 1000 100 success
2 1009 80 success
3 1010 100 failed
4 1011 50 success
6 1012 50 success
7 1013 100 failed
i would like to join two tables, select fields, process sum count and filter like this
e_id e_name amount_sum total_counts total_success_amount success_count
1001 Tom 280 3 180 2
1002 Parker 100 2 100 2
1003 Rohan 100 1 0 0
this is what i tried
use card;
SELECT COUNT(orders.order_id) as `total_counts`,
COUNT(CASE WHEN transactions.status = 'success' THEN 1 END) as `success_count`,
SUM(0 + transactions.amount) as `amount_sum`, orders.e_id,
orders.e_name
FROM orders
LEFT JOIN transactions
ON transactions.order_id=orders.order_id
GROUP BY (orders.e_id), (orders.order_id),
(orders.e_name), (transactions.amount), (transactions.status);
i tried many queries also not able to achieve it. Suggest me query to get my operation.

I have 3 tables Flight_schedule, Flights and third is Route I need a stored procedure in SQL which give the cheapest flight on a given date

I have 3 tables Flight_schedule, Flights and third is Route I need a stored procedure in SQL which give the cheapest flight on a given date.
When the parameter date is passed to procedure suppose 2 February so the result would be the lowest fare flight on the 2 Feb.
Here is the code where I have joined the tables and passed the parameter to stored procedure but when I am confused in the condition part.
Create proc spCheapestFlight
#FLIGHT_DATE DATE
AS
BEGIN
SELECT Flight_schedule.FlightDate,Flight_schedule.Departure,route.source, route.destination,
Flight_schedule.Arrival
,Flight_schedule.Fare,Flights.Flight_name
FROM Flight_schedule
inner join route ON Flight_schedule.Route_id=route.Route_id inner join
Flights on Flights.Flight_id=Flight_schedule.Flight_id
where Flight_schedule.FlightDate = #FLIGHT_DATE
END
Flight_schedule
F_Id
Flight_id
Total_Fare
FlightDate
Departure
Arrival
Route_Id
Fare
10000
1
1001
2022-02-01
09:30:30.0000000
11:20:45.0000000
100
7500.8
10001
2
1002
2022-02-02
09:45:30.0000000
11:55:45.0000000
101
7000.9
10002
3
1003
2022-02-03
10:30:30.0000000
12:20:45.0000000
102
5111.5
10003
4
1004
2022-02-04
11:30:30.0000000
14:20:45.0000000
103
5500.9
10004
5
1005
2022-02-05
12:30:30.0000000
15:20:45.0000000
104
9000.7
10005
1
1006
2022-02-06
13:30:30.0000000
16:20:45.0000000
105
8675.5
10006
2
1007
2022-02-07
14:30:30.0000000
17:20:45.0000000
106
4000.5
10007
3
1008
2022-02-08
15:30:30.0000000
18:20:45.0000000
107
4100.5
10008
4
1009
2022-02-09
16:30:30.0000000
19:20:45.0000000
101
4000.3
10009
2
1006
2022-02-10
06:30:30.0000000
08:20:45.0000000
108
4000.3
Flights
Flight_id
Flight_name
Capacity
1
Vistara
30
2
Indigo
30
3
SpiceJet
30
4
Go_First
30
5
Air India
30
Route
route_id
source
destination
100
Mumbai
Delhi
101
Delhi
Ahmedabad
102
Ahmedabad
Delhi
103
Ahmedabad
Mumbai
104
Chennai
Mumbai
105
Chennai
Goa
106
Chennai
Delhi
107
Goa
Delhi
108
Bangalore
Delhi
109
Hyderabad
Delhi
your data does not show more than 1 flight per day, in addition there is no need for table Flights and table Route to get result, you should join table FlightSchedule with itself in order to get the minimum fare. your problem can be solve with table-value function(TVF). you should change you PROCEDURE as follows:
CREATE PROCEDURE spCheapest_Costliest_Flight (#FlightDate DATE)
AS
SELECT FS.FlightDate,FS.Departure,route.source, route.destination,
FS.Arrival ,T.Fare,Flights.Flight_name
FROM Flight_schedule FS
inner join route ON FS.Route_id=route.Route_id
inner join Flights on Flights.Flight_id=FS.Flight_id
inner join (select FlightDate FlightDate,MIN(Fare) Fare
from Flight_schedule GROUP BY FlightDate) T
ON T.FlightDate=FS.FlightDate and T.FlightDate=#FlightDate and FS.FlightDate=#FlightDate
GO

Showing Two Fields With Different Timeline in the Same Date Structure

In the project I am currently working on in my company, I would like to show sales related KPIs together with Customer Score metric on SQL / Tableau / BigQuery
The primary key is order id in both tables. However, order date and the date we measure Customer Score may be different. For example the the sales information for an order that is released in Feb 2020 will be aggregated in Feb 2020, however if the customer survey is made in March 2020, the Customer Score metric must be aggregated in March 2020. And what I would like to achieve in the relational database is as follows:
Sales:
Order ID
Order Date(m/d/yyyy)
Sales ($)
1000
1/1/2021
1000
1001
2/1/2021
2000
1002
3/1/2021
1500
1003
4/1/2021
1700
1004
5/1/2021
1800
1005
6/1/2021
900
1006
7/1/2021
1600
1007
8/1/2021
1900
Customer Score Table:
Order ID
Customer Survey Date(m/d/yyyy)
Customer Score
1000
3/1/2021
8
1001
3/1/2021
7
1002
4/1/2021
3
1003
6/1/2021
6
1004
6/1/2021
5
1005
7/1/2021
3
1006
9/1/2021
1
1007
8/1/2021
7
Expected Output:
KPI
Jan-21
Feb-21
Mar-21
Apr-21
May-21
June-21
July-21
Aug-21
Sep-21
Sales($)
1000
2000
1500
1700
1800
900
1600
1900
AVG Customer Score
7.5
3
5.5
3
7
1
I couldn't find a way to do this, because order date and survey date may/may not be the same.
For sample data and expected output, click here.
I think what you want to do is aggregate your results to the month (KPI) first before joining, as opposed to joining on the ORDER_ID
For example:
with order_month as (
select date_trunc(order_date, MONTH) as KPI, sum(sales) as sales
from `testing.sales`
group by 1
),
customer_score_month as (
select date_trunc(customer_survey_date, MONTH) as KPI, avg(customer_score) as avg_customer_score
from `testing.customer_score`
group by 1
)
select coalesce(order_month.KPI,customer_score_month.KPI) as KPI, sales, avg_customer_score
from order_month
full outer join customer_score_month
on order_month.KPI = customer_score_month.KPI
order by 1 asc
Here, we aggregate the total sales for each month based on the order date, then we aggregate the average customer score for each month based on the date the score was submitted. Now we can join these two on the month value.
This results in a table like this:
KPI
sales
avg_customer_score
2021-01-01
1000
null
2021-02-01
2000
null
2021-03-01
1500
7.5
2021-04-01
1700
3.0
2021-05-01
1800
null
2021-06-01
900
5.5
2021-07-01
1600
3.0
2021-08-01
1900
7.0
2021-09-01
null
1.0
You can pivot the results of this table in Tableau, or leverage a case statement to pull out each month into its own column - I can elaborate more if that will be helpful

Incremental count in SQL Server 2005

I am working with a Raiser's Edge database using SQL Server 2005. I have written SQL that will produce a temporary table containing details of direct debit instalments. Below is a small table containing the key variables for the question I'm going to ask, with some fictional data:
Donor_ID Instalment_ID Instalment_Date Amount
1234 1111 01/01/2011 £5.00
1234 1112 01/02/2011 £0.00
1234 1113 01/03/2011 £5.00
1234 1114 01/04/2011 £5.00
1234 1115 01/05/2011 £0.00
1234 1116 01/06/2011 £0.00
2345 2111 01/01/2011 £0.00
2345 2112 01/02/2011 £5.00
2345 2113 01/03/2011 £5.00
2345 2114 01/04/2011 £0.00
2345 2115 01/05/2011 £0.00
2345 2116 01/06/2011 £0.00
As you will see, some of the values in the Amount column are £0.00. This can occur when a donor has insufficient funds in their account, for example.
What I'd like to do is write a SQL query that will create a field containing an incremental count of consecutive £0.00 payments that resets after a non-£0.00 payment or after a change in Donor_ID. I have reproduced the above data below, with the field I'd like to see.
Donor_ID Instalment_ID Instalment_Date Amount New_Field
1234 1111 01/01/2011 £5.00
1234 1112 01/02/2011 £0.00 1
1234 1113 01/03/2011 £5.00
1234 1114 01/04/2011 £5.00
1234 1115 01/05/2011 £0.00 1
1234 1116 01/06/2011 £0.00 2
2345 2111 01/01/2011 £0.00 1
2345 2112 01/02/2011 £5.00
2345 2113 01/03/2011 £5.00
2345 2114 01/04/2011 £0.00 1
2345 2115 01/05/2011 £0.00 2
2345 2116 01/06/2011 £0.00 3
To help clarify what I'm looking for, I think what I'm looking to do would be similar to a winning streak field on a list of a football team's results. For example:
Opponent Score Winning_Streak
Arsenal 1-0 1
Liverpool 0-0
Swansea 3-1 1
Chelsea 2-1 2
Fulham 4-0 3
Stoke 0-0
Man Utd 1-3
Reading 2-1 1
I've considered various options, but have made no progress. Unless I've missed something obvious, I think that a solution more advanced than my current SQL programming level might be required.
If I am thinking about this problem correctly, I believe that you want a row number when the Amount is 0.00 pounds.
Select 0 as As InsufficientCount
, Donor_ID
, Installment_ID
, Amount
From [Table]
Where Amount > 0.00
Union
Select Row_Number() Over (Partition By Donor_ID Order By Installment_ID)
, Donor_ID
, Installment_ID
, Amount
From [Table]
Where Amount = 0.00
This union select should only give you 'ranks' where the Amount equals 0.
Am calling your new field streakAmount
ALTER TABLE instalments ADD streakAmount int NULL;
Then, to update the value:
UPDATE instalments
SET streakAmount =
(SELECT
COUNT(*)
FROM
instalments streak
WHERE
streak.donor_id = instalments.donor_id
AND
streak.instalment_date <= instalments.instalment_date
AND
(streak.instalment_date >
-- find previous instalment date, if any exists
COALESCE(
(
SELECT
MAX(instalment_date)
FROM
instalments prev
WHERE
prev.donor_id = instalments.donor_id
AND
prev.amount > 0
AND
prev.instalment_date < instalments.instalment_date
)
-- otherwise min date
, cast('1753-1-1' AS date))
)
)
WHERE
amount = 0;
http://sqlfiddle.com/#!6/a571f/18

SQL Query to join two columns of a table with other tables

I have 3 tables as shown in the diagram:
The test data in each of these tables is as given below:
ACCOUNT_GROUP
GroupID Name
101 Bank Accounts
105 Cash-in-hand
113 Indirect Expenses
120 Purchase Accounts
122 Sales Accounts
125 Sundry Creditors
ACCOUNT_MASTER
AccID Name GroupID
1001 RBS A/C 23456 101
1002 HSBC A/C 123456 101
1003 CASH A/C 105
1004 DISCOUNT 113
1005 CASH SALES 122
1006 CASH PURCHASE 120
1007 JOHNSON 125
ACCOUNT_TXNS
TxnID TxnDate FromAccID ToAccID Amt CrDr
1 20-Jul-2011 1002 1003 250000 C
2 20-Jul-2011 1001 1002 985241 C
3 20-Jul-2011 1005 1003 65451 C
4 20-Jul-2011 1006 1003 412874 D
5 20-Jul-2011 1007 1003 521400 C
6 20-Jul-2011 1003 1007 200 D
I want to get the account names of both FromAccID and ToAccID and their group names in a single query like this:
TxnID TxnDate FromAcc FromAccGroup ToAcc ToAccountGroup Amt CrDr
1 20-Jul-2011 HSBC A/C 123456 Bank Accounts CASH A/C Cash-in-hand 250000 C
2 20-Jul-2011 RBS A/C 23456 Bank Accounts HSBC A/C 123456 Bank Accounts 985241 C
3 20-Jul-2011 CASH SALES Sales Accounts CASH A/C Cash-in-hand 65451 C
4 20-Jul-2011 CASH PURCHASE Purchase Accounts CASH A/C Cash-in-hand 412874 D
5 20-Jul-2011 JOHNSON Sundry Creditors CASH A/C Cash-in-hand 521400 C
6 20-Jul-2011 CASH A/C Cash-in-hand JOHNSON Sundry Creditors 200 D
Kindly help me to achieve this.
You can use the same table more than once in a single query, just use aliases.
Something like
SELECT *
FROM ACCOUNT_TXNS txns INNER JOIN
ACCOUNT_MASTER fromAcc ON txns.FromAccID = fromAcc.AccID INNER JOIN
ACCOUNT_GROUP fromAccGrp ON fromAcc.GroupID = fromAccGrp.GroupID INNER JOIN
ACCOUNT_MASTER toAcc ON txns.ToAccID = toAcc.AccID INNER JOIN
ACCOUNT_GROUP toAccGrp ON toAcc.GroupID = toAccGrp.GroupID