MS Access Query to records with same data in different fields in the same row - sql

The title is a bit confusing but I'll explain my problem here:
So i have a database table with millions of lines of spending data broken up into different time fields (period1 - period14). Now what i need to do is write a query that will return the records where the spending in one period is equal to the spending in a different period within the same record. So basically that means if i have a reecord where the spending in period1 is $100 and then the spending in period5 is also $100, it will add that record to a new table. I tried something like the code below but since I'm very new to access it is rather complex/inefficient and also doesn't do what i need it to.
INSERT INTO Contracts
SELECT *
FROM SPENDDETAIL
WHERE (SPENDDETAIL.Period1 = SPENDDETAIL.Period2 OR SPENDDETAIL.Period3 [...] OR SPENDDETAIL.Period14)
AND (SPENDDETAIL.Period1 <> 0 OR SPENDDETAIL.Period2 <> 0 [...] OR SPENDDETAIL.Period14 <> 0);
Any help much appreciated, thanks!
Oh also i know this code snippet would only return the records where the period1 spend equals the spend from any of the other periods it was just a beginning attempt at making the query do what i need it to.

Something along these lines might get you started:
SELECT Id, Value, COUNT(*) FROM
(SELECT Id AS Id, 1 AS Period, Period1 AS Value FROM SPENDDETAIL
UNION ALL
SELECT Id AS Id, 2 AS Period, Period2 AS Value FROM SPENDDETAIL
UNION ALL
SELECT Id AS Id 3 AS Period, Period3 AS Value FROM SPENDDETAIL
etc...) x
GROUP BY Id, Value
HAVING COUNT(*) > 1
Where Id is some unique identifier for each row of the data (assuming there is such a thing).
This will give you a list of Ids and matching values.

Related

Calculating the percentage of different types of customer feedback in each quarter

The problem statement is: I have a table (order_t) which has customer feedback (one column) and quarter number (as another column).
Using a CTE, I need to calculate the percentage of number of customer feedback in each category as well as the total number of customer feedback in each quarter.
After this happens, I need the percentage of different types of customer feedback (like good, bad, ok, very good, very bad) but using CTE.
How can I solve this statement?
I try to solve customer feedback as
WITH total_feedback AS
(
SELECT *
COUNT(CUSTOMER_FEEDBACK), QUARTER NUMBER
FROM
table1
GROUP BY
2
)
But I'm unable to calculate the first half portion, i.e. percentage of different types of customer feedback in each quarter using CTE.
How can I do that?
Find the file of the data
What you could do, and I'll keep the example as close to the code you provided as possible, is the following - using 2 CTE's:
WITH total_feedback AS (
SELECT COUNT(CUSTOMER_FEEDBACK) AS total_feedback, QUARTER_NUMBER
FROM table1
GROUP BY 2
),
category_feedback AS (
SELECT COUNT(CUSTOMER_FEEDBACK) AS feedback_count, CUSTOMER_FEEDBACK, QUARTER_NUMBER
FROM table1
GROUP BY 2, 3
)
SELECT
category_feedback.CUSTOMER_FEEDBACK,
category_feedback.QUARTER_NUMBER,
(feedback_count / total_feedback.total_feedback) * 100 AS feedback_percentage
FROM category_feedback
INNER JOIN total_feedback
ON category_feedback.QUARTER_NUMBER = total_feedback.QUARTER_NUMBER

SQL query with summed statistical data, grouped by date

I'm trying to wrap my head around a problem with making a query for a statistical overview of a system.
The table I want to pull data from is called 'Event', and holds the following columns (among others, only the necessary is posted):
date (as timestamp)
positionId (as number)
eventType (as string)
Another table that most likely is necessary is 'Location', with, among others, holds the following columns:
id (as number)
clinic (as boolean)
What I want is a sum of events in different conditions, grouped by days. The user can give an input over the range of days wanted, which means the output should only show a line per day inside the given limits. The columns should be the following:
date: a date, grouping the data by days
deliverySum: A sum of entries for the given day, where eventType is 'sightingDelivered', and the Location with id=posiitonId has clinic=true
pickupSum: Same as deliverySum, but eventType is 'sightingPickup'
rejectedSum: A sum over events for the day, where the positionId is 4000
acceptedSum: Same as rejectedSum, but positionId is 3000
So, one line should show the sums for the given day over the different criteria.
I'm fairly well read in SQL, but my experience is quite low, which lead to me asking here.
Any help would be appreciated
SQL Server has neither timestamps nor booleans, so I'll answer this for MySQL.
select date(date),
sum( e.eventtype = 'sightingDelivered' and l.clinic) as deliverySum,
sum( e.eventtype = 'sightingPickup' and l.clinic) as pickupSum,
sum( e.position_id = 4000 ) as rejectedSum,
sum( e.position_id = 3000 ) as acceptedSum
from event e left join
location l
on e.position_id = l.id
where date >= $date1 and date < $date2 + interval 1 day
group by date(date);

Total number of records and their reason SQL Server

I want to write a query that get total number of records (booking) using the COUNT(*) function. I have a column Type in the database and in the next column I want to show type of record e.g output of query be like
Total Booking -> 10
Booking Type -> 3 wedding ceremony, 4 Birthday Party, 3 family Event (this will be in single cell next to total Booking)
Someone please help me.. Thanks
Try this out, it will give you the total count of each type, with an overall total at the top.
SELECT 'Total Bookings', COUNT(*)
FROM BookingTable
UNION
SELECT [Type], COUNT(*)
FROM BookingTable
GROUP BY [Type]

Access SQL query. 3 date reoccurences in seven days on an id

Anyones help on this would be very much appreciated..
I have a Table with lots of fields but the two I want to query is
'MachineId' <- Id Field
'DateLogged' <- Date and time Service Call Logged
The MachineId represents a physical machine onsite. What i'm after is, has the machine had 3 calls logged to it within 7 days. Not just in the last seven days but in the lifetime of the machine.
I wanted to return a table with the MachineId's that hit this criteria.
I'm banging my head. Any help would be much appreciated.
You can do this with a self-join and aggregation. The idea is to find any matching record within a week after each row in the table. Then aggregate by the original row and count the number of matches:
select t.MachineId, t.DateLogged, count(*) as NumIncidents
from table t inner join
table t2
on t.MachineId = t2.MachineId and
t2.DateLogged between t.DateLogged and dateadd("d", 6, t.DateLogged)
group by t.MachineId, t.DateLogged
having count(*) >= 3;

How do I count data from 2 different tables by date

I have 2 tables with no relations, both tables have different number of columns, but there are a few columns that are the same but hold different data. I was able to create a function or view of only the data I wanted, but when I try to count the data by filtering the date, I always get the wrong count in return. Let me explain by showing the 2 functions and what I try to do:
Function 1
ID - number from 1 to 8
data sent - YES or NO
Date - date value
Function 2
ID - number from 1 to 8
data sent - yes or no
date - date value
Upon running both separately, I get all the rows from the tables and everything looks good.
Then I try to add the following to each function:
select
count([data sent]), ID
from function1
Where (date between #date1 and #date2)
group by ID
The above statement works great and gives me the right result for each function.
Now I thought what if I want to add those 2 functions into one and get the count from both functions on 1 page.
So I created the following function:
Function 3
select
count(Function1.[data sent]) as Expr1,
Function1.id,
count(Function2.[data sent]) as Expr2,
Function1.date
from
Function1
LEFT OUTER JOIN
Function2 on Function1.id = Function2.id
Where
(Function1.date between #date1 and #date2)
group by
Function1.id
Upon running the above, I get the following table:
ID Expr1 Expr2
On both Expr1 and Expr2, I get results which I am not sure where they come from. I guess something is being multiplied by 100000 since one table holds almost 15000 rows and the other around 5000 rows.
What I would like to know first is if it possible at all to be able to filter by date and count records from both table at the same time. If anyone need more information please let me know and I will be glad to share and explain more.
Thank you
The LEFT OUTER JOIN is taking each row of the left table, finding ALL of the rows in the right table with the same id field, and creating that many rows in the result table. Since id isn't what we usually think of as an identity field (it looks more like a "deviceId" or something), you'll get lots of matches for each one. Repeat 15000 times and you get your combinatorial explosion.
Tip: To debug things like this, you can create sample tables with a tiny subset of the real data, say 10 rows from each, and run your query on them. You'll see the issue immediately.
It's possible to filter by date. It's hard to recommend an actual solution without better understanding your phrase "I want to add those 2 functions into one and get the count from both functions on 1 page".
Why can't you create a temporary table for each function then join them together?
Maybe subqueries can help you to achieve what you want:
SELECT
ID = COALESCE(f1.ID, f2.ID),
Date = COALESCE(f1.Date, f2.Date),
f1.Expr1,
f2.Expr2
FROM (
SELECT
ID,
Date,
Expr1 = COUNT([data sent])
FROM Function1
WHERE Date BETWEEN #date1 AND #date2
GROUP BY
ID,
Date
) f1
FULL JOIN (
SELECT
ID,
Date,
Expr2 = COUNT([data sent])
FROM Function2
WHERE Date BETWEEN #date1 AND #date2
GROUP BY
ID,
Date
) f2
ON f1.ID = f2.ID AND f1.Date = f2.Date
This query also uses full (outer) join instead of left join, in case the right side of the join contains rows that have no match in the left side (and you want those rows).