Join two tables with additional field in one table [duplicate] - sql

This question already has answers here:
SQL JOIN and different types of JOINs
(6 answers)
Closed 3 years ago.
I would like to join together two tables with additional columns.
First table is for number of products despatched by product
** Table 1 - Despatches **
Month ProductID No_despatched
Jan abc 10
Jan def 15
Jan xyz 12
The second table is for the number of products returned by product, but also an additional column by return reason
** Table 2 - Returns **
Month ProductID No_returned Return_reason
Jan abc 2 Too big
Jan abc 3 Too small
Jan xyz 1 Wrong colour
I would like to join the tables to show returns and despatched on the same row with the number of despatched being duplicated if there are multiple return reasons for the same product.
** Desired output **
Month ProductID No_despatched No_returned Return_reason
Jan abc 10 2 Too big
Jan abc 10 3 Too small
Jan xyz 12 1 Wrong colour
Hope this makes sense...
Thanks in advance!
afk

This seems like a basic JOIN:
select r.month, r.productid, d.no_despathed, r.no_returned, r.return_reason
from returns r join
despatches d
on r.month = d.month and r.productid = d.productid;
The results don't seem particularly useful, because some products are missing (those with no returns). And the amounts are duplicated if there is more than one return record.

just use join
select a.*,b.No_returned,.Return_reason from
table1 join table2 on a.ProductID=b.ProductID
and a.month=b.month
In case of duplicate you may use distinct

Changing the order of clauses in your question produces the result.
with additional columns.
SELECT Table1.Month, Table1.ProductID, Table1.NoDespatched, Table2.NoReturned, Table2.ReturnReason
join two tables
FROM Table1 LEFT JOIN Table2
ON Table1.Month=Table2.Month AND Table1.ProductID=Table2.ProductID
We use a LEFT JOIN because, presumably a product can be dispatched without being returned, but nobody can return a product you didn't send out.

Related

Bigquery - Best way to transpose rows into multiple columns [duplicate]

This question already has answers here:
How to: For each unique id, for each unique version, grab the best score and organize it into a table
(1 answer)
Change direction of table in BigQuery
(2 answers)
Closed 4 months ago.
I have data in below format
CustomerID
ID
Year
value
1000
1477
2022
True
1000
1477
2021
True
1000
1474
2022
Credit
1000
1474
2021
Debit
1000
1464
2022
Total Amount
1000
1464
2021
Net Amount
I would like to transpose this data for a particular Customer ID at each ID level for each year. Below is the expected Output
CustomerID
Year
ID_1477
ID_1474
ID_1464
1000
2022
True
Credit
Total Amount
1000
2021
True
Debit
Net Amount
Below is the query I have written to get this. I basically performed a self join and extracted the required elements into separate columns
SELECT
ele_1477.CustomerID,
ele_1477.Year,
ele_1477.value as ID_1477,
ele_1474.value as ID_1474,
ele_1464.value as ID_1464
FROM
(select * from table where id=1477 ) ele_1477
LEFT OUTER JOIN (select * from table where id=1474 ) ele_1474 ON ele_1477.CustomerID=ele_1474.CustomerID and ele_1477.Year=ele_1474.Year
LEFT OUTER JOIN (select * from table where id=1464 ) ele_1464 ON ele_1477.CustomerID=ele_1464.CustomerID and ele_1477.Year=ele_1464.Year
But my question here is, I am not sure how effective this query is. I have another 150 set of IDs for a CustomerID that needs to be transposed. Does that mean should i do a self join 150 times? Looking for a best possible solution to achieve this
You can use a PIVOT and a dynamic SQL for your purpose.
For your sample data, you can pivot your table like below.
SELECT *
FROM sample_table
PIVOT (ANY_VALUE(Value) ID FOR ID IN ('1477', '1474', '1464'));
I have another 150 set of IDs for a CustomerID that needs to be transposed.
And also you can use EXECUTE IMMEDIATE instead of writing down 150 IDs in your real data.
EXECUTE IMMEDIATE FORMAT("""
SELECT * FROM sample_table PIVOT (ANY_VALUE(Value) ID FOR ID IN ('%s'))
""", (SELECT STRING_AGG(DISTINCT ID, "','") FROM sample_table));
Query results of above two queries

Extract only variables which is greater than other table in influxDB

I am using influxDB and I would like to extract some values which is greater than certain threshold in other table.
For example, I have two tables as shown in below.
Table A
Time value
1 15
2 25
3 9
4 22
Table B
Time threshold
1 16
2 12
3 13
4 15
Give above two tables, I would like to extract three values which is greater than first row in Table B. Therefore what I want to have is as below.
Time value
2 25
4 22
I tried it using below sql query, but it didn't give any correct result.
select * from data1 where value > (select spec from spec1 limit1);
Look forward to your feedback.
Thanks.
Integrate the condition in an inner join:
select * from tableA as a
inner join tableB as b on a.id=b.id and a.value > b.threshold
When your time column doesn't only include integer values, you have to format the time and join on a time range. Here is an example:
SQL join on time range

How calc Rank with this data in my database?

i have table that store questions each question have different answers and each answer have different weight and now i want to Calculation the rank but i don't now how do this.please help me
i use sql server
i have this table stored answers and weight of each answer
AdminQuesAns
=======================
Id QuesId Ans Value
10 1000 Yes 10
11 1000 somewhat 5
12 1000 No 0
10 1001 Yes 0
12 1001 No 10
and this table store Customer answers
AdminRank
==================================
Id SDId QuesId AnsValue
1 100 1000 10
2 100 1001 0
You can use the below query.
1.
Select SDId ,b.QuesId,
((sum(a.AnsValue) *100)/(Select sum(c.value)
from AdminQuesAns c where c.QuesId =b.QuesId))as'Rank'
from AdminRank a join AdminQuesAns b on a.QuesId=b.QuesId and value=AnsValue
group by SDId ,b.QuesId
This is how I'd go about it.
This has an inner query which gets the max value for each question, then the outer query pairs those with the values from the individual answers, sums across the questions and calculates one as a percentage of the other.
I'm also grouping by SDId, on the assumption that that is the ID of the person filling out the survey.
SELECT
ar.SDId,
100 * cast(sum(ar.AnsValue) as numeric(5,2)) / sum(mv.maxValue) as Rank
FROM
AdminRank ar
JOIN
(
SELECT
qa.QuesId,
max(qa.Value) as maxValue
FROM
AdminQuesAns qa
GROUP BY
qa.QuesId
) mv on ar.QuesId = mv.QuesId
GROUP BY
ar.SDId
Depending on your data types you may be able to remove the cast part.

Apportioning data into new columns

Morning,
I am quite new to SQL Server 2008 so I was wondering if you could help me.
I currently have:
SELECT
c.code, d.date, d.date_previous,
CAST(d.date-date_previous as int) AS Days,
d.units, d.cost
FROM table1 AS d
INNER JOIN table2 AS p ON d.ID = p.ID
INNER JOIN table3 AS c ON p.c_id = c.ID
WHERE date_previous > '31/12/2012'
This is bringing back one row per invoice received after 31/12/2012. The aim is to get the following columns:
Code Jan data Feb data Mar data etc...
one unique code per line (so I'm assuming row partitioning is required)
Where a bill has a period of 3 months with, for example, 300 units, I'd like that separated out across 3 months (100 in each)
I'm aware I'd probably need to use a pivot function and some temp tables but I'm not that advanced yet.

Need to repeat and calculate values in a single Select statement

I hope that someone can help me with my issue. I need to create in a single SELECT statement (the system that we use has some pivot tables in Excel that handle one single SELECT) the following:
I have a INL (Invoice Lines) table, that has a lot of fields, but the important one is the date.
INL_ID DATE
19 2004-03-15 00:00:00.000
20 2004-03-15 00:00:00.000
21 2004-03-15 00:00:00.000
22 2004-03-16 00:00:00.000
23 2004-03-16 00:00:00.000
24 2004-03-16 00:00:00.000
Now, I also have a ILD (Invoice Line Details) that are related by an ID field to the INL table. From the second table I will need to use the scu_qty field to "repeat" values from the first one in my results sheet.
The ILD table values that we need are:
INL_ID scu_qty
19 1
20 1
21 1
22 4
23 4
Now, with the scu_qty I need to repeat the value of the first table and also add one day each record, the scu_qty is the quantity of days of the services that we sell in the ILD table.
So I need to get something like (i'm going to show the INL_ID 22 that you can see has a value different of 1 in the SCU_QTY). The results of the select has to give me something like:
INL_ID DATE
22 2004-03-15 0:00:00
22 2004-03-16 0:00:00
22 2004-03-17 0:00:00
22 2004-03-18 0:00:00
In this information I only wrote the fields that need to be repeated and calculated, of course I will need more fields, but will be repeated from the INL table, so I don't put them so you don't get confused.
I hope that someone can help me with this, it's very important for us this report. Thanks a lot in advance
(Sorry for my English, that isn't my first language)
SELECT INL_ID, scu_qty, CalculatedDATE ...
FROM INL
INNER JOIN ILD ON ...
INNER JOIN SequenceTable ON SequenceTable.seqNo <= ILD.scu_qty
ORDER BY INL_ID, SequenceTable.seqNo
Depending on your SQL flavour you will need to lookup date manipulation functions to do
CalculatedDATE = {INL.DATE + SequenceTable.seqNo (days)}
select INL.INL_ID, `DATE`
from
INL
inner join
ILD on INL.INL_ID = ILD.INL_ID
inner join (
select 1 as qty union select 2 union select 3 union select 4
) s on s.qty <= ILD.scu_qty
order by INL.INL_ID
In instead of that subselect you will need a table if quantity is a bit bigger. Or tell what is your RDBMS and there can be an easier way.