Calculate difference between two dates and count the number of occurrences - sql

I am trying to calculate the difference between two dates and in the same query trying to count the frequency of occurence.
SELECT DATEDIFF(day,[Date1],[Date2]) AS 'Mydate'
, count ([Mydate])
FROM Table1
group
by 'Mydate'
I am expecting the query to calculate and count but getting an error msg "Each GROUP BY expression must contain at least one column that is not an outer reference."
what I am expecting is, something like this:
Mydate Count
0 5
1 4
2 5
Can someone help me please? Thanks

First of all this doesn't look like MySQL rather SQL Server. Secondly you can't use the alias in Count() function like that. Rather say count(*)
SELECT DATEDIFF(day,[Date1],[Date2]) AS 'Mydate',
Count (*)
FROM Table1
GROUP BY DATEDIFF(day,[Date1],[Date2])

You cannot group by an alias:
SELECT 'Mydate', Cnt
FROM (SELECT DATEDIFF(day, [Date1], [Date2]) AS 'Mydate',
Count(*) Cnt
FROM Table1) T1
GROUP BY 'Mydate'

Related

Oracle SQL how to find count less than avg

my code is like :
SELECT
number,
name,
count(*) as "the number of correct answer"
FROM
table1 NATURAL JOIN table2
WHERE
answer = 'T'
GROUP BY
number,
name
HAVING
count(*) < avg(count(*))
ORDER BY
count(*);
Here I want to find the group with count less than the average number of count for each group, but here I failed to use HAVING or WHERE, could anyone help me?
How can I only select the 1 name1 2 since avg of count is (2+6+7)/3 = 5 and only 2 is less than avg.
number name count
1 name1 2
2 name2 6
3 name3 7
I would advise you to never use natural joins. They obfuscate the query and make the query a maintenance nightmore.
You can use window functions:
SELECT t.*
FROM (SELECT number, name,
COUNT(*) as num_correct,
AVG(COUNT(*)) OVER () as avg_num_correct
FROM table1 JOIN
table2
USING (?). -- be explicit about the column name
WHERE answer = 'T'
GROUP BY number, name
) t
WHERE num_correct < avg_num_correct;
As with your version of the query, this filters out all groups that have no correct answers.
I would place your current query logic into a CTE, and then tag on the average count in the process:
WITH cte AS (
SELECT number, name, COUNT(*) AS cnt,
AVG(COUNT(*)) OVER () AS avg_cnt
FROM table1
NATURAL JOIN table2
WHERE answer = 'T'
GROUP BY number, name
)
SELECT number, name, cnt AS count
FROM cte
WHERE cnt < avg_cnt;
Here we are using the AVG() function as an analytic function, with the window being the entire aggregated table. This means it will find the average of the counts per group, across all groups (after aggregation). Window functions (almost) always evaluate last.

Select query to show timestamp (HH:MM:SS) colomn with group by HH (ORACLE QUERY)

I am trying to create select query in oracle to get following result from my_table
table contents timestamp_coloumn and count coloumn, records in timestamp_colomn are getting inserted are by minute bases.
Tried query:- something like this
select to_char(timestamp_coloumn ,'HH24:MI:SS') as TS , count as count
from my_table
group by to_char(timestamp_coloumn ,'HH24');
Error:-
ORA-00979: not a GROUP BY expression
if ,I match select and and group by statement like following it works but, i couldn't achieve my expected result (i dont know if is right to query like that)
select to_char(timestamp_coloumn ,'HH24:MI:SS') as TS , count as count
from my_table
group by to_char(timestamp_coloumn ,'HH24:MI:SS');
Expected result (Hourly timestamp and count is grouped and summed for all records present in that hour):-
timestamp_coloumn count
--------------------------
07:01:23 4
08:01:36 3
09:01:44 6
10:01:10 5
Please help me with this query
You can use MIN():
select min(to_char(timestamp_coloumn ,'HH24:MI:SS')) as TS, count(*)
from my_table
group by to_char(timestamp_coloumn ,'HH24');
Or make the two expressions match:
select to_char(timestamp_coloumn ,'HH24') as TS, count(*)
from my_table
group by to_char(timestamp_coloumn ,'HH24');

count the total number of column field appeared more than once in database

I am trying to run the query to get the total number of repetitions (appeared more than once) for one column called "abc" . I am trying this but not able to achieve.
select COUNT(SELECT DISTINCT card_no, COUNT(*) AS cnt )
please help, thanks in advance.
For Example below is the column :
cards
123,
456
,123
Result:
Count
1
As 123 appeared more than once.
You want the number of distinct values in the column that are repeated at least once, is that right?
SELECT COUNT(dupes)
FROM (SELECT card_no AS dupes, COUNT(*) cnt FROM table_name
GROUP BY card_no HAVING COUNT(*) > 1) A
Edit for explanation.
The inner query SELECT card_no AS dupes, COUNT(*) cnt FROM table_name GROUP BY card_no HAVING COUNT(*) > 1 returns only those values that are repeated in your table. The aliases on the columns are necessary because it's a subquery. You can run this query independently of the outer query to see what results it returns.
You have to have the group by on any field that you don't want to aggregate when you're aggregating other fields (e.g. performing a count of records), and the HAVING part is to filter out anything that isn't duplicated (i.e. has a count of 1). HAVING is the way to apply filtering on aggregated fields that you can't have in a WHERE.
The outer query SELECT COUNT(dupes)... is merely counting the number of card_no values returned by the inner query. Since these are grouped, it gives the number of distinct values that are duplicated.
A at the end there sets up an alias for the subquery so that it can be referenced like it's an actual table elsewhere in the query. This is necessary for any subquery in the FROM clause of another query. Effectively the select in the outer query reads SELECT COUNT(A.dupes)... and without the alias A there would be no way to qualify where the dupes field is being referenced from (even though in this case it's implied).
It's also worth noting that the field COUNT(*) cnt isn't required in the SELECT part of the subquery as it isn't being used anywhere else in the query. It will work just as effectively without it, as long as you still have the GROUP BY and HAVING clauses.
SELECT
card_no, COUNT(*) AS "Occurrences"
FROM
YourTable
GROUP BY card_no
HAVING
COUNT(*) > 1

Adding count in select query

I am trying to find a query that would give me a count of another table in the query. The problem is that I have no idea what to set where in the count part to. As it is now it will just give back a count of all the values in that table.
Select
ID as Num,
(select Count(*) from TASK where ID=ID(Also tried Num)) as Total
from ORDER
The goal is to have a result that reads like
Num Total
_________________
1 13
2 5
3 22
You need table aliases. So I think you want:
Select ID as Num,
(select Count(*) from TASK t where t.ID = o.ID) as Total
from ORDER o;
By the way, ORDER is a terrible name for a table because it is a reserved work in SQL.
You can do it as a sub query or a join (or an OVER statement.)
I think the join is clearest when you are first learning SQL
Select
ID as Num, count(TASK.ID) AS Total
from ORDER
left join TASK ON ORDER.ID=TASK.ID
GROUP BY ORDER.ID

SELECT *, COUNT(*) in SQLite

If i perform a standard query in SQLite:
SELECT * FROM my_table
I get all records in my table as expected. If i perform following query:
SELECT *, 1 FROM my_table
I get all records as expected with rightmost column holding '1' in all records. But if i perform the query:
SELECT *, COUNT(*) FROM my_table
I get only ONE row (with rightmost column is a correct count).
Why is such results? I'm not very good in SQL, maybe such behavior is expected? It seems very strange and unlogical to me :(.
SELECT *, COUNT(*) FROM my_table is not what you want, and it's not really valid SQL, you have to group by all the columns that's not an aggregate.
You'd want something like
SELECT somecolumn,someothercolumn, COUNT(*)
FROM my_table
GROUP BY somecolumn,someothercolumn
If you want to count the number of records in your table, simply run:
SELECT COUNT(*) FROM your_table;
count(*) is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by
If what you want is the total number of records in the table appended to each row you can do something like
SELECT *
FROM my_table
CROSS JOIN (SELECT COUNT(*) AS COUNT_OF_RECS_IN_MY_TABLE
FROM MY_TABLE)