How to join three select queries which has one common column - sql

I have three select queries as below which gives a respective output
select DATE_FORMAT(table1.value_date,'%b')as Month,
DATE_FORMAT(table1.value_date,'%Y') as Year,
table1.open as Open
from index_main as table1
join ( select min(`value_date`) `value_date`
from index_main
group by month(`value_date`), year( `value_date`)
) as table2 on table1.`value_date` = table2.`value_date`
Output columns - Month,year,open
select DATE_FORMAT(table1.value_date,'%b')as Month,
DATE_FORMAT(table1.value_date,'%Y') as Year,
table1.close as Open
from index_main as table1
join ( select max(`value_date`) `value_date`
from index_main group by month(`value_date`), year( `value_date`)
) as table2 on(table1.`value_date` = table2.`value_date`)
Output columns - Month,year,close
select DATE_FORMAT(table1.value_date,'%b')as Month,
DATE_FORMAT(table1.value_date,'%Y') as Year,
max(table1.high) as High
FROM `index_main` as table1
GROUP BY table1.month,table1.year
ORDER BY year(table1.value_date) desc, month(table1.value_date) desc
Output columns - Month,year,high,low
I want to join these three select queries based on the common columns i.e month & year.
My final result should have the following columns - month,year,open,close,high,low.

Try this.
First create 3 views, one with each query (vw1, vw2 and vw3). Then use a query like this:
SELECT vw1.Month, vw1.Year, Open, Close High FROM vw1 LEFT join vw2 on vw1.Year=vw2.Year and vw1.Month=vw2.Month LEFT JOIN vw3 on vw1.Year=vw3.Year and vw1.Month=vw3.Month
Hope this helps you.

Related

SQL query to sum by group and inner join two tables

I have two tables like so:
Each row in both tables is uniquely identified by the columns week and city.
I want to create one table with 5 columns (week, value_a, value_b, value1, value2) and 3 rows (1 row for each week, with the value columns being summed across each city). The final table should look exactly like this:
sum_a is the sum of value a for each week across all cities, sum_b is the sum of value_b across all cities and so on.
Here is my SQL query:
SELECT *
FROM table1
INNER JOIN table2
ON table1.week = table2.week AND
table1.city = table2.city
If you need to sum column relied by join you just need to sum your tables before to avoid repeat data
Considere that if you have a week in your table 1 and not in the table 2 the data will not be shawn in your example
SELECT
A1.week,
A1.city,
A1.value1,
A1.value2,
A2.value1,
A2.value2
FROM (
SELECT
Week,
city,
sum(value1),
sum(value2)
FROM table1
GROUP BY Week, city
) A1
INNER JOIN (
SELECT
Week,
city,
sum(valueA),
sum(valueB)
FROM table2
GROUP BY Week, city
) A2
ON a1.week = a2.week AND a1.city = a2.city
the below query can give you output as expected:
SELECT table1.week, sum(value_a) as sum_a, sum(value_b) as sum_b, sum(value1) as sum_1, sum(value2) as sum_2
FROM table1
INNER JOIN table2 ON table1.week = table2.week AND table1.city = table2.city
group by table1.week
Query can be validated by checking the link db<>fiddle<>example

How to aggregate different CTEs in outer query SQL

i am trying to join two ctes to get the difference in performance of different countries and group on id here is my example
every campaign can be done in different countries, so how can i group by at the end to have 1 row per campaign id ?
CTE 1: (planned)
select
country
, campaign_id
, sum(sales) as planned_sales
from table x
group by 1,2
CTE 2: (Actual)
select
country
, campaign_id
, sum(sales) as actual_sales
from table y
group by 1,2
outer select
select
country,
planned_sales,
actual_sales
planned - actual as diff
from cte1
join cte2
on campaign_id = campaign_id
This should do it:
select
cte1.campaign_id,
sum(cte1.planned_sales),
sum(cte2.actual_sales)
sum(cte1.planned_sales) - sum(cte2.actual_sales) as diff
from cte1
join cte2
on cte1.campaign_id = cte2.campaign_id and cte1.country = cte2.country
group by 1
I would suggest using full join, so all data is included in both tables, not just data in one or the other. Your query is basically correct but it needs a group by.
select campaign_id,
sum(cte1.planned_sales) as planned_sales
sum(cte2.actual_sales) as actual_sales,
(coalesce(sum(cte1.planned_sales), 0) -
coalesce(sum(cte2.actual_sales), 0)
) as diff
from cte1 full join
cte2
using (campaign_id, country)
group by campaign_id;
That said, there is no reason why the CTEs should aggregate by both campaign and country. They could just aggregate by campaign id -- simplifying the query and improving performance.

'Arithmetic overflow error converting expression to data type int' when left join temp tables

When trying to LEFT JOIN two temp tables I have, I'm getting the arithmetic overflow error. When doing a UNION, there's no issue, nor is there an issue when I change my SELECT statement to not use SUM functions. Here are my two tables:
SELECT SUM(count) count
, EventType
, month
FROM #engine_final
GROUP BY EventType
, month
UNION ALL
SELECT SUM(count) count
, EventType
, month
FROM #circumvent_final
GROUP BY EventType
, month
And here's the results:
So what I'm attempting to do is SUM my counts, grouped by month, with the following query:
SELECT SUM(ef.count) AS EngineStarts
, SUM(cf.count) AS Circumventions
FROM #engine_final ef
LEFT JOIN #circumvent_final cf ON ef.month = cf.month
But this is when I'm confronted with the error. I thought maybe I had hit the limit for INT, but my numbers only reach about 260 million, so that can't be it. What am I missing?
Your join multiplies the rows. You should pre-aggregate in subqueries first, then join:
SELECT ef.month, ef.EngineStarts, cf.Circumventions
FROM (
SELECT month, SUM(count) EngineStarts
FROM #engine_final
GROUP BY month
) ef
LEFT JOIN (
SELECT month, SUM(cf.count) AS Circumventions
FROM #circumvent_final
GROUP BY month
) cf ON ef.month = cf.month
I am unsure whether you need where clauses in the subquery to filter on the eventType - you can easily add them if that's needed.
If you have months in cf that are not in ef, and the other way around too, you might want to consider a FULL JOIN instead of a LEFT JOIN:
SELECT
COALESCE(ef.month, cf.month) month,
COALESCE(ef.EngineStarts, 0) EngineStarts,
COALESCE(cf.Circumventions, 0) Circumventions
FROM (
SELECT month, SUM(count) EngineStarts
FROM #engine_final
GROUP BY month
) ef
FULL JOIN (
SELECT month, SUM(cf.count) AS Circumventions
FROM #circumvent_final
GROUP BY month
) cf ON ef.month = cf.month

SQL Server - Select multiple Columns Group By 1 Column

I have looked at many examples of selecting many columns but only grouping by 1 column and mine seem to give me duplicate results. See below I would like to select all the columns in my table but would like to only GROUP BY VehicleId. On the screenshot you'll see that the results are actually not grouped by VehicleId.
Any idea on what I am doing wrong?
Try 1:
SELECT
h.*,
TotalFines = 1,
TotalIncidents = 1,
TotalVehicleAllocations = 1,
TotalVehicleConditions = 1,
TotalMileageApplications = 1
FROM
(
SELECT h1.VehicleId FROM [dbo].[VehicleHistory] h1 GROUP BY h1.VehicleId
) GroupedList
INNER JOIN [dbo].[VehicleHistory] h ON GroupedList.VehicleId=h.VehicleId
ORDER BY
h.VehicleId;
Try 2:
SELECT t1.* FROM VehicleHistory t1
INNER JOIN
(
SELECT VehicleId FROM VehicleHistory GROUP BY VehicleId
) t2
ON t1.VehicleId=t2.VehicleId
Both queries produce the same results with duplicate rows for each VehicleId as per below:
Here's my expected results below. The results are a query produced by Entity Framework. But I would like to rewrite the linq query into T-SQL:
This is because you are gtouping in subquery (which would be same as SELECT DISTINCT h1.VehicleId FROM [dbo].[VehicleHistory] h1):
SELECT h1.VehicleId FROM [dbo].[VehicleHistory] h1 GROUP BY h1.VehicleId
and then you are joining in on that column, which can cause duplicates to occur (you have duplicate IDs in VehicleHistory).
All you need to do is:
SELECT VehicleId,
MAX(DateUpdated) DateUpdated, --or other aggregate function
--rest of your columns in appropriate aggreagte functions
FROM VehicleHistory
GROUP BY VehicleId

Need Help on Inner Join two Query

Hi Guys can you help me out to create this inner joint query.
the idea is I need to first get which is the top 3 highest keyword count then show that count of keyword per month (I need the Month Number only)
SELECT ReportRaw.Keyword, Format([DateApplying],'m') AS appdate, Count(ReportRaw.Keyword) AS CountOfKeyword1
FROM
(
SELECT TOP 3 Count(Keyword) AS CountOfKeyword,Keyword
FROM ReportRaw
GROUP BY Keyword
ORDER BY Count(Keyword) DESC;
) as T1
INNER JOIN ReportRaw
ON T1.Keyword = ReportRaw.Keyword
GROUP BY ReportRaw.Keyword, Format([DateApplying],'m') ;
It looks like that semicolon (;) after DESC. Assuming this is SQL Server
Made a tiny update to the query to get that month number:
SELECT #ReportRaw.Keyword, DATEPART(MONTH, [DateApplying]) AS appdate,
Count(#ReportRaw.Keyword) AS CountOfKeyword1
FROM
(
SELECT TOP 3 Count(Keyword) AS CountOfKeyword,Keyword
FROM #ReportRaw
GROUP BY Keyword
ORDER BY Count(Keyword) DESC
) as T1
INNER JOIN #ReportRaw
ON T1.Keyword = #ReportRaw.Keyword
GROUP BY #ReportRaw.Keyword, DATEPART(MONTH, [DateApplying]) ;