Running this line of code
Activity.uniq.select(:ip).where("created_at > NOW() - INTERVAL 1 DAY").count
Returns the number of all lines (without the uniquness filter) although the SQL is correct (with the DISTINCT keyword)
If I run this command in 2 steps:
c = Activity.uniq.select(:ip).where("created_at > NOW() - INTERVAL 1 DAY")
c.size
Then I get the right count.
How can it be?
Thank you
Generally DISTINCT will remove duplicate results from a result set but it won't do any grouping. Since you have one row in a COUNT result, you won't see any effect. What you really want is this:
SELECT COUNT(DISTINCT activities.ip) FROM activities WHERE ...
Note that you want a count of the distinct activities, not a distinct count.
I'm not sure how you'd manage to emit this SQL using ActiveRecord. You may need to resort to using the ActiveRecord connection directly and use select_value for such an unusual sort of inquiry unless you can coach select to do it for you.
Related
I need someone who can explain me about "group function is not allowed here" because I don't understand it and I would like to understand it.
I have to get the product name and the unit price of the products that have a price above the average
I initially tried to use this, but oracle quickly told me that it was wrong.
SELECT productname,unitprice
FROM products
WHERE unitprice>(AVG(unitprice));
search for information and found that I could get it this way:
SELECT productname,unitprice FROM products
WHERE unitprice > (SELECT AVG(unitprice) FROM products);
What I want to know is why do you put two select?
What does group function is not allowed here mean?
More than once I have encountered this error and I would like to be able to understand what to do when it appears
Thank you very much for your time
The phrase "group function not allowed here" is referring to anything that is in some way an "aggregation" of data, eg SUM, MIN, MAX, etc et. These functions must operate on a set of rows, and to operate on a set of rows you need to do a SELECT statement. (I'm leaving out UPDATE/DELETE here)
If this was not the case, you would end up with ambiguities, for example, lets say we allowed this:
select *
from products
where region = 'USA'
and avg(price) > 10
Does this mean you want the average prices across all products, or just the average price for those products in the USA? The syntax is no longer deterministic.
Here's another option:
SELECT *
FROM (
SELECT productname,unitprice,AVG(unitprice) OVER (PARTITION BY 1) avg_price
FROM products)
WHERE unitprice > avg_price
The reason your original SQL doesn't work is because you didn't tell Oracle how to compute the average. What table should it find it in? What rows should it include? What, if any, grouping do you wish to apply? None of that is communicated with "WHERE unitprice>(AVG(unitprice))".
Now, as a human, I can make a pretty educated guess that you intend the averaging to happen over the same set of rows you select from the main query, with the same granularity (no grouping). We can accomplish that either by using a sub-query to make a second pass on the table, as your second SQL did, or the newer windowing capabilities of aggregate functions to internally make a second pass on your query block results, as I did in my answer. Using the OVER clause, you can tell Oracle exactly what rows to include (ROWS BETWEEN ...) and how to group it (PARTITION BY...).
I have a requirement to get a distinct count of people we offered a job, problem is since we can offer multiple jobs on potential candidate , when i write my query its counting multiple offers. Requirement is to count only the first offer, any subsequent offer should not count. any suggestions on this?
You can use this COUNT(DISTINCT...) like the following :
SELECT a.p_id, b.p_name, c.p_desc,
COUNT(DISTINCT CASE WHEN a.date BETWEEN TRUNC(ADD_MONTHS(LAST_DAY(sysdate),-4) + 1) AND
ADD_MONTHS(LAST_DAY(TO_DATE(sysdate)),-1) ...
I'm new here so please be gentle, my first question after using this website for a long time regards the below:
I'm trying to create a sum of count of events in the past 30 days:
select key, sum((COALESCE(count(*),0)))
from table
Where date>= '2016-08-13'
And date<= '2016-09-11'
group by key;
but the sum doesn't seem to work. i'm looking at the last 30 days, and i would like to count any row that exists for each key, and then sum the counts (i need to count on a daily basis and then sum all day's count).
If you can offer any other way to deal with this issue i'm open for suggestions!
Many thanks,
Shira
You can't nest aggregate functions in HQL (or SQL). However, if you just want a count of records falling within range for each key, then you can simply just use COUNT(*):
select key, count(*)
from table
where date >= '2016-08-13' and
date <= '2016-09-11'
group by key;
It looks like there was a couple things wrong with your code.
I've written this for you, haven't tested it but it passes the syntax test.
SELECT COUNT(key) AS Counting FROM tblname
WHERE date>= '2016-08-13'
AND date<= '2016-09-11'
GROUP BY key;
And this might help you. You should definitely be using COUNT for this query.
I'm not sure if it's related but there might be an issue with calling a field 'key' I kept receiving syntax errors for it.
Hope I was able to help!
-Krypton
well this is my problem
i use 2 source
first query (select * from servera.databasea.tablea)
secund query(select id, modifiedon from serverb.databaseb.tableb)
sort first query, sort second query
merge join at left join
condition split is.. isnull(idtableb) then i do insert (insert ont serverb)
!isnull(idtableb) && modifiedontableb<modifiedontablea then update(on server b)
it works ok with a few of rows but i work with more of 50000 and it take more than 2 hours on sort and it get error
well my another way was doing
sort on oledbsource on right-click at show advancededitor and on
input and output properties on ole db source output i choose issorted changed to true
on output columns to id i changed to
sortkeyposition to 1
(i didnt put nothing to modifiedon)
so i did these steps for 2 oledbsource
(oledb for server1, and server 2)
it work a lot of faster it finished at 5 minuts and do insert (always)
condition split doesn't work now :s cuz always going to insert
so i on condition split added parse (DT_DBDATE) and it continues being equal (only inserts)
never going to update after i chended mofidiedon parse (DT_DATE) and it continue being equal. then my question is
(i dont want to use sort) how can i do condition split works?
The Sort step takes long because you are running low on memory for your sort operation. This means it will start sorting on disk, and that is horribly slow. Options to this is to use some 3rd party sorting components like NSort.
Otherwise you can do the following:
In order for your MERGE to work your inputs need to be sorted, both in the query, and using the SortKeyPosition. Also they need to be sorted the same.
Your queries should read:
SELECT * FROM servera.databasea.tablea ORDER BY id, modifiedon
SELECT id, modifiedon FROM serverb.databaseb.tableb ORDER BY id, modifiedon
Now set the IsSorted to TRUE, set SortKeyPosition 1 to id
In your MERGE step, use id for join key.
Now in your conditional split, you can use your two output cases.
Please note, if you have MULTIPLE rows per id, you need something more to sort/join on, so that you don't get stuff in the wrong order.
I have a table with a CreatedDate column. I want to order by the rows that have been in the database the longest, but need to determine the number of days by subtracting it from DateTime.Now.
I realise this is doable simply by ordering by the CreatedDate, but I need to do more than that.
I need to order the items by the amount of times they have been used within a period of time, in effect getting the most popular items.
So what I want to do is first determine the number of days, and after that divide this by the number of times each item has been used.
Step 1)
orderby (DateTime.Now.Subtract(t.CreatedDate.Value).Days)
Step 2)
orderby (t.UsedCount/DateTime.Now.Subtract(t.CreatedDate.Value).Days)
This results in the following error:
Method 'System.TimeSpan Subtract(System.DateTime)' has no supported translation to SQL.
Oddly, "Subtract()" doesn't work, but Minus does.
try:
orderby (t.UsedCount/(DateTime.Now - t.CreatedDate.Value).Days)
(Tested in LINQPad using the "master" database)
from sp in Spt_monitors
orderby sp.Io_busy / (DateTime.Now - sp.Lastrun).Days
select sp