SQL query that calculates historical average and checks if current value is greater multiple than 3 - sql

I am try to calculate the average since the last time stamp and pull all records where the average is greater than 3. My current query is:
SELECT AVG(BID)/BID AS Multiple
FROM cdsData
where Multiple > 3
and SqlUnixTime > 1492225582
group by ID_BB_RT;
I have a table cdsData and the unix time is april 15th converted. Finally I want the group by calculated within the ID as I show. I'm not sure why it's failing but it says that the field Multiple is unknown in the where clause.

I am try to calculate the average since the last time stamp and pull all records where the average is greater than 3.
I think your intention is correctly stated as follows, "I am trying to calculate the average since the last time stamp and select all rows where the average is greater than 3 times the individual bid".
In fact, a still better restatement of your objective would be, "I want to select all rows since the last time stamp, where the bid is less than 1/3rd the average bid".
For this, the steps are as follows:
1) A sub-query finds the average bid divided by 3, of rows since the last time stamp.
2) The outer query selects rows since the last time stamp, where the individual bid is < the value returned by the sub-query.
The following SQL statement does that:
SELECT BID
FROM cdsData
WHERE SqlUnixTime > 1492225582
AND BID <
(
SELECT AVG(BID) / 3
FROM cdsData
WHERE SqlUnixTime > 1492225582
)
ORDER BY BID;

1)
SQL is evaluated backwards, from right to left. So the where clause is parsed and evaluate prior to the select clause. Because of this the aliasing of AVG(BID)/BID to Multiple has not yet occurred.
You can try this.
SELECT AVG(BID)/BID AS Multiple
FROM cdsData
WHERE SqlUnixTime > 1492225582
GROUP BY ID_BB_RT Having (AVG(BID)/BID)>3 ;
Or
Select Multiple
From (SELECT AVG(BID)/BID AS Multiple
FROM cdsData
Where SqlUnixTime > 1492225582 group by ID_BB_R)X
Where multiple >3
2)
Once you corrected the above error, you will be having one more error:
Column 'BID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
To correct this you have to insert BID column in group by clause.

Related

How to write an SQL query to get max number of counts for the most number of travelling of a user within a month

I have been given a task by my manager to write a SQL query to select the max number of counts (no of records) for a user who has travelled the most within a month provided that if the user travels multiple places on the same date, then it should be counted as one. For instance, if you look at the following table design; according to this scenario, my query must return me a count of 2. Although traveller_id "1" has traveled three times within a month, but he traveled to Thailand and USA on the same date, that is why its count is reduced to 2.
I have also developed my logic for this query but I am unable to write it due to lack of syntax knowledge. I split up this query into 3 parts:
Select All records from the table within a month using the MONTH function of SQL
Select All distinct DateTime records from the above result so that the same DateTime gets eliminated.
Select max number of counts for the traveller who visited most places.
Please help me in completing my query. You can also use a different approach from mine.
You can use the count aggregation in a cte then select top(1):
with u as
(select traveller_id,
count(distinct visit_date) as n
from travellers_log
where visit_date between '2022-03-01' and '2022-03-31'
group by traveller_id)
select top(1) traveller_id, name, n from u inner join table_travellers
on u.traveller_id = table_travellers.id
order by n desc;

Avoid double counting - only count first occurrence in table

I am trying to do a count by month of the total number of items (serialnumber) that appears in inventory.
This usually can be easily solved with distinct, however, I only want to count if it is the first occurrence that it appears (first insert).
This query gets me most of the way there.
select date_trunc (‘month’,date) as Date,productid, count(distinct serialnumber) from inventory
where date_trunc(‘month’,date)>= ‘2016-01-01’ and productID in ('1','2') and status = ‘INSERT’
group by date_trunc(‘month’,date), productid
order by date_trunc(‘month’,date) desc
But I realize I am double/triple/quadruple counting some serial numbers because an item can reappear in our inventory multiple times over the course of its lifecycle.
The query above covers these scenarios since the serial numbers appear once:
Shows up as new
Shows up as used
Below are the use cases where I realize I may be double/triple/quadruple counting:
Shows up as new then comes back around as used (no limit to how many times it can appear used)
Shows up used then comes back again as used (no limit to how many times it can appear used)
Here's an example I ran into.
(Note: I have added the condition column to better illustrate this). But the particular serial number has been in inventory three times (first as new, then as used twice)
Date
ProductID
Count
Condition
7-1-21
1
1
u
11-1-18
1
1
u
2-1-17
1
1
n
In my current query results, each insert gets counted (once in Feb 2017, once in Nov 2018 and once in July 2021).
How can I amend my query to make sure I'm only counting the very first instance (insert) a particular serial number appears in the inventory table?
In the subquery calculate first insert date only of each product/item using min aggregate function. Then count the items on that result:
select Date, productid, count(serialnumber)
from (
select min(date_trunc(‘month’,date)) as Date, productid, serialnumber
from inventory
where date_trunc(‘month’,date) >= ‘2016-01-01’
and productID in ('1','2')
and status = ‘INSERT’
group by productid, serialnumber
) x
group by Date, productid
order by Date desc;

Big Query SQL - Group into every n numbers

I have a table that includes a column called minutes_since. It is an integer containing the number of minutes since a pre-defined event. Multiple rows maybe fall within the same minute.
I want to group and aggregate the rows into every n minutes. For example, I want to get the average of another column for all rows occurring within 5 minute intervals.
How could this be achieved in big query standard sql?
#standardSQL
SELECT
MIN(minutes_since) minute_start,
MAX(minutes_since) minute_end,
AVG(value) value_avg
FROM `project.dataset.table`
GROUP BY DIV(minutes_since - 1, 5)

Running a complex loop query in PostgreSQL

I have one problem in PostgreSQL.
This is my table (this table does not showing all data in image).
What is my requirement is:
Step 1 : find count of value (this is a column in table) Order by value for today date. So it will be like this and I did it.
Step 2 : find count of value for last 30 days starting from today. I am stuck here. Also one another thing is included in this step --
Example : today has 10 count for a value - kash, this will be 10x30,
yesterday had 4 count for the same value , so will be 4x29, so the total sum would be
(10x30) + (4x29) = 416.
This calculation is calculated for each and every value.
This loop execute for 30 times (as I said before last 30 days starting from today). Take today as thirtieth day.
Query will just need to return two columns with value and sum, ordered by the sum.
Add a WHERE clause to your existing query:
WHERE Timestamp > current_date - interval '30' day;
As far as ordering by the sum, add an ORDER BY clause.
ORDER BY COUNT(*) DESC.
I do not believe that you will need a loop (CURSOR) for this query.

MS Access SQL statement count usage

I am new to SQL. I was given a coursework to report data of usage over the last 2 month. Can someone help me with the SQL statement?
SELECT COUNT(Member_ID,Non_Member_Name) AS Pool_usage_last_2_months
FROM Use_of_pool
WHERE DATEDIFF(‘2012-04-21’,’2012-02-21’)
What I meant to do is to count the total number of member usage(member_ID) and non member usage(no ID,name only) from the last two months and then output the name and date and time,etc. on the same report. Is there any SQL statement to output that kind of information? Correction/Suggestions are welcomed.
You need a different WHERE clause. Assuming your Use_of_pool table includes a Date/Time field, date_field:
WHERE date_field >= #2012-02-21# AND date_field <= #2012-04-21#
If date_field values can include a time component other than midnight, advance the end date range by one day to capture all the possible Date/Time values from Apr. 21:
WHERE date_field >= #2012-02-21# AND date_field <= #2012-04-22#
That should restrict the rows to match what I think you want. It should offer fast performance with an index on date_field.
I'm unclear about the count(s) you want ... whether it is to be one count for all visits (both member and non-member), or separate counts for members and non-members.
Edit: If each row of the table represents a visit by one person, you can simply count the rows to determine the number of visits during your selected time frame.
SELECT Count(*) AS CountOfVisits
FROM Use_of_pool
WHERE date_field >= #2012-02-21# AND date_field <= #2012-04-21#
Notice each visit by the same person will contribute to CountOfVisits, which is what I think you want. If you wanted to know how many different people visited, we will need a different approach.
Edit2:
It sounds like you can use Member_ID and Non_Member_Name to distinguish between member and nonmember visits. Member_ID is Null for nonmembers and non-Null for members. And Non_Member_Name is Null for members and non-Null for nonmembers.
If that is true, try this query to count member and nonmember visits separately.
SELECT
Sum(IIf(Member_ID Is Not Null, 1, 0)) AS member_visits,
Sum(IIf(Non_Member_Name Is Not Null, 1, 0)) AS non_member_visits
FROM Use_of_pool
WHERE date_field >= #2012-02-21# AND date_field <= #2012-04-21#
Aggregate functions of SQL use all the data in a column (more precisely, all the data your WHERE clause selects) to produce a single datum. COUNT gives you the number of data rows that matched your WHERE clause. So for example:
SELECT COUNT(*) AS Non_members FROM Use_of_pool WHERE Member_ID IS NULL
will give you the number of times the pool was used by a non-member, and
SELECT COUNT(DISTINCT Member_ID) AS Members FROM Use_of_pool
will give you the number of members who have used the pool at least once (the DISTINCT tells the database engine to ignore duplicates when counting).
You can expand the WHERE clause to further specify what you want to count. If "last two months" means the current and previous calendar month, you'll need:
... WHERE DateDiff("m",Date_field,Date())<=1
If it means a rolling 2-month period, I'd approximate that with 60 days and say
... WHERE DateDiff("d",Date_field,Date())<60
(Replace Date_field with the name of the field containing the date.)
If you want to count rows according to multiple different criteria, or output both aggregate data and individual data, you'll be best off using separate SELECT statements.