Joining different queries into 1 query in MS Access - database

For the past few days I've been trying everything that I know and everything that I could find on the internet. But I can't seem to figure it out and this turns me banana's.
I have 3 different MS Access Queries.
QUERY 1
SELECT First([Master Data Results 2013 - 2016].[Winner]) AS Player, Count([Master Data Results 2013 - 2016].[Winner]) AS Won
FROM [Master Data Results 2013 - 2016]
GROUP BY [Master Data Results 2013 - 2016].[Winner]
HAVING (((Count([Master Data Results 2013 - 2016].[Winner]))>1));
This query counts every tennis match won by player for a periode of 3 years
QUERY 2
SELECT First([Master Data Results 2013 - 2016].[Loser]) AS Player, Count([Master Data Results 2013 - 2016].[Loser]) AS Lost
FROM [Master Data Results 2013 - 2016]
GROUP BY [Master Data Results 2013 - 2016].[Loser]
HAVING (((Count([Master Data Results 2013 - 2016].[Loser]))>1));
This query counte everyt tennis match lost by player for a periode of 3 years
QUERY 3
INSERT INTO Master ( Lost )
SELECT Winner.*, Loser.Lost
FROM Loser INNER JOIN Winner ON Loser.Player = Winner.Player;
I have created a "Master" table. In this table I want to put the combined results of QUERY1 and QUERY 2.
The Master table looks like this.
So I want al the players that are in QUERY 1 in the Players column in the Master table.
The numbers counted as a result of QUERY 1 in the Won column in the Master table and the numbers counted as a result of QUERY 2 in the Lost column in the Master table.
When I run each query seperatly than it works,but I want to put all this into 1 query for ease of use.

You can use UNION query for combining results of Query 1 and 2, column [Lost] in query 1 = 0, column [Won] in query 2 = 0 and then aggregate this query, using Sum on [Lost] and [Won]. Something like this:
INSERT INTO Master (Player, Won, Lost)
SELECT Player, Sum(Won), Sum(Lost) FROM (
SELECT First([Master Data Results 2013 - 2016].[Winner]) AS Player,
Count([Master Data Results 2013 - 2016].[Winner]) AS Won,
0 AS Lost
FROM [Master Data Results 2013 - 2016]
GROUP BY [Master Data Results 2013 - 2016].[Winner]
HAVING (((Count([Master Data Results 2013 - 2016].[Winner])) > 1))
UNION
SELECT First([Master Data Results 2013 - 2016].[Loser]) AS Player,
0 as Won,
Count([Master Data Results 2013 - 2016].[Loser]) AS Lost
FROM [Master Data Results 2013 - 2016]
GROUP BY [Master Data Results 2013 - 2016].[Loser]
HAVING (((Count([Master Data Results 2013 - 2016].[Loser])) > 1))
)
GROUP BY Player

Related

In SQL Server, how do I get the date of an event from a table and the date the previous event happened?

I'm using Microsoft SQL Server 2016 (SP2) (13.0.5026.0 (X64). I have a query that joins a people table with a contacts table. The people table has the client detail and the contacts table tells us the last time that client has made a contact.
The below query links the tables and gives me the client ID and the date they made contact
SELECT
DP.dim_person_ID AS [Dim_Person_ID],
CAST(FC.CONTACT_DTTM AS date) AS [Contact Date]
FROM
Child_Social.Fact_Contacts FC
INNER JOIN
CHILD_SOCIAL.DIM_Person DP ON FC.dim_person_ID = DP.Dim_Person_ID
If they made multiple contacts they will return a row for each one and the output will look like this
Person_ID
Contact Date
1
01/01/2023
1
01/10/2022
1
01/07/2022
1
01/04/2022
1
01/01/2022
2
02/01/2023
2
02/10/2022
2
02/07/2022
2
02/04/2022
2
02/01/2022
What I'm trying to do is to add a column to the query that shows the previous contact date as well eg return an output like
Person ID
Contact Date
Previous Contact Date
1
01/10/2022
01/07/2022
1
01/07/2022
01/04/2022
2
02/10/2022
02/07/2022
2
02/07/2022
02/04/2022
I'm unsure how to create a join/sub query that will calculate a previous episode (rather than a most recent episode or a first episode, just the previous one).
Any help or guidance gratefully received

Google Data Studio Table: Dividing Data that has 2 different Years

I need to produce a table that has Quotes win%. The formula is #won divide by #sent.
My problem is, there are quotes that are won within a year but were sent in different years.
(My data comes from BigQuery)
The data looks like this:
Sale Sent Won
sale1 2019 2020
sale2 2019 2020
sale3 2016 2017
sale4 2017 2019
sale5 2020 2020
sale6 2020 2020
sale7 2018 2018
sale8 2016 2016
sale9 2015 2016
sale10 2016 2017
sale11 2016 2018
sale12 2018 2019
I'd like to be able to create a table in data studio like this:
Year SENT WON WIN%
2016 4 2 50%
2017 1 2 200%
2018 2 2 100%
2019 2 2 100%
2020 2 4 200%
I would love to see if this is possible in google data studio. Any suggestion is highly appreciated.
Added a Google Data Studio Report to demonstrate, as well as a GIF showing the process below.
One approach is to restructure the Data at the Data Set and use Calculated Fields in a Table:
1) Data Transformation
The data needs to be transformed from the current Wide structure to a Long data structure. One way it can be achieved in Google Sheets is by using the formula below (Sheet1 represents the input sheet; consult embedded Google Sheet for clarification):
=ArrayFormula(QUERY({
{Sheet1!A:A,IF(LEN(Sheet1!A:A),"Sent",""),Sheet1!B:B};
{Sheet1!A:A,IF(LEN(Sheet1!A:A),"Won",""),Sheet1!C:C}
},"Select * Where Col3 is not null Label Col2 'Dimension', Col3 'Year'",1))
2) Table
- Dimension: Year
- Sort: Year in Ascending order
- Metrics: Add the 3 calculated fields below:
3) Calculated Fields
The formulas below create the metrics used in the Table above (Formula 3.1 and 3.2 need to be added at the Data Source-level, while 3.3 can be added at the Chart-level if required):
3.1) SENT
COUNT(CASE
WHEN REGEXP_MATCH(Dimension, "Sent") THEN Year
ELSE NULL END)
3.2) WON
COUNT(CASE
WHEN REGEXP_MATCH(Dimension, "Won") THEN Year
ELSE NULL END)
3.3) WIN%
WON / SENT

Query to find records with more than one date

I'm trying to build a query for a MS SQL database that will find records with more than one year but not the records with only one.
Lets say I have a car dealership and I have 1 Chevy from 2015 and 2 from 2017 then I would want to find Chevy 2015 1 and chevy 2017 2 but if I have a three Fords from 2018 and only 2018 then I don't want that at all.
I have tweeked with groups and joins but I don't get any where. So I need Select from table something. I'm leaning toward a pivot table but not sure what to do. Thanks for the help
MyTable Contents
Model year count
Chevy 2012 1
Chevy 2012 1
Chevy 2015 1
Ford 2018 1
Ford 2018 1
Ford 2018 1
Buick 2017 1
Lexus 2017 1
Lexus 2015 1
Desired Result Set
Chevy 2012 2
Chevy 2015 1
Lexus 2017 1
Lexus 2015 1
Because it has 2 different years for the model
The below query should help you. Need not hardcode model values.
Select T.Model,T.[year] ,count(T.[year])
from T
join (select distinct * from T) S on T.model = S.model and T.year!=S.year
group by T.Model,T.[year]
You need to use SUM function and group by on subquery,Because there might be Multiple count on count column. then join itself and distinct to exclude duplicate data.
Select distinct t1.*
from (
SELECT Model,[year] ,sum([count]) totle
FROM T
group by Model,[year]
) t1
inner join T t2 on t1.Model = t2.Model and t1.[year] !=t2.[year]
sqlfiddle:http://sqlfiddle.com/#!18/e8756/55
Note:[table],[year] are keyword in sql avoid naming it as column name

Join two tables depending on date sequence

In SQL Server 2008, I want to join two tables depending on date sequence. More specifically, I need to left join Payments table to Profiles table by the following rules:
UserId has to be matched.
Every record in Payments matches the record in Profiles with the closest Profiles.CreationDate before Payments.PayDate.
For a simplified example,
Table Payments:
UserId PayDate Amount
1 2012 400
1 2010 500
2 2014 600
Table Profiles:
UserId CreationDate Address
1 2009 NY
1 2015 MD
2 2007 NJ
2 2013 MA
3 2008 TX
Desired Result:
UserId CreationDate PayDate Amount Address
1 2009 2010 500 NY
1 2009 2012 400 NY
2 2013 2014 600 MA
It's guaranteed that a user have at least 1 Profiles record before he pays. Another restriction is that I not authorized to write anything into the database.
I idea is first left join Payments with Profiles, then within the record group matching each (UserId, PayDate) tuple, sort it by CreationDate, then select the last record. But I don't know how to implement it in SQL language, or are there any better ways to do this merge?
Use Outer Apply to do this.
SELECT py.UserId,
CreationDate,
PayDate,
Amount,
Address
FROM Payments py
OUTER APPLY (SELECT TOP 1 *
FROM Profiles pr
WHERE py.UserId = pr.UserId
and PayDate> CreationDate
ORDER BY CreationDate desc) cs
SQLFIDDLE DEMO

One to many Relationship in SQL Server Analysis Services

I have these tables:
DimDate (PK: DateKey, other attributes)
FactActivationCodes (PK: ActivationCode, IssuedDateKey (FK to DimDate)
FactExpirations (PK: ActivationCode + ExpirationType, FK: ActivationCode to FactActivationCodes)
I set up measures that count the number of rows in
Issued Count (count of rows in FactActivationCodes)
Expired Count (count of distinct ActivationCodes in FactExpirations)
The idea is that the FactActivationCodes has one activation code, with a date when it was issued. The activation code can get expired year after year (and then renewed) so it would have a row for expiration in FactExpirations (one each year)
I put some test rows in the tables; I put 3 rows in FactActivationCodes (different IssuedDate for each) , and only 2 in FactExpirations. When I browse the cube, and I am looking at the count of Issued on columns, and the Issued Date (dimension) on rows, it looks like this:
Issued Date
January 2008 1
February 2008 1
March 2008 1
But then, when I add the Expired Count, I was hoping to see the 'expired column' count with only the ones that match the 'Activation Code' like so, because of the one to many relationship between the two fact tables:
Issued Date Expired Date
January 2008 1 1
February 2008 1 1
March 2008 1 0
But instead, I a cross join of everything like so, with the totals of expired:
Issued Date Expired Date
January 2008 1 2
February 2008 1 2
March 2008 1 2
April 2008 2
May 2008 2
June 2008 2
And onwards, for every date entry in my Date Dimensions... I guess I'm not doing the relationship correctly... how can I get the expected result?
The answer to use referenced relationship: http://technet.microsoft.com/en-us/library/ms166704.aspx

Resources