rails postgreSQL cannot get this query to work (SUM, Group Order) - ruby

This query work when I try it in SQLite:
Transaction.where(:paid => true).select("created_at, SUM(amount) amount").group("DATE(created_at)").order('created_at')
But when I run it with postgreSQL it doesn'y work.
Heres the error message:
ActiveRecord::StatementInvalid: PGError: ERROR: column "transactions.created_at" must appear in the GROUP BY clause or be used in an aggregate function : SELECT created_at, SUM(amount) as amount FROM "transactions" WHERE ("transactions"."paid" = 't') GROUP BY DATE(created_at) ORDER BY created_at
Anyone who can help me?
Thanks in advance

You have to either use DATE(created_at) in the select clause, or use created_at in the group by clause.

You're selecting created_at, sum(amount), ordering by created_at, but are grouping by date(created_at). The latter will disallow the use of anything but the grouped by fields and aggregates except in the join/where clause.
To fix, either group by created_at, or select and order by date(created_at) instead of created_at.

Related

Laravel - Get the last entry of each UID type

I have a table that has 100's of entries for over 1000 different products, each identified by a unique UID.
ID UID MANY COLUMNS CREATED AT
1 dqwdwnboofrzrqww1 ... 2018-02-11 23:00:43
2 dqwdwnboofrzrqww1 ... 2018-02-12 01:15:30
3 dqwdwnbsha5drutj5 ... 2018-02-11 23:00:44
4 dqwdwnbsha5drutj5 ... 2018-02-12 01:15:31
5 dqwdwnbvhfg601jk1 ... 2018-02-11 23:00:45
6 dqwdwnbvhfg601jk1 ... 2018-02-12 01:15:33
...
I want to be able to get the last entry for each UID.
ID UID MANY COLUMNS CREATED AT
2 dqwdwnboofrzrqww1 ... 2018-02-12 01:15:30
4 dqwdwnbsha5drutj5 ... 2018-02-12 01:15:317
6 dqwdwnbvhfg601jk1 ... 2018-02-12 01:15:33
Is this possible in one DB call?
I have tried using DB as well as Eloquent but so far I either get zero results or the entire contents of the Table.
Andy
This is easy enough to handle in MySQL:
SELECT t1.*
FROM yourTable t1
INNER JOIN
(
SELECT UID, MAX(created_at) AS max_created_at
FROM yourTable
GROUP BY UID
) t2
ON t1.UID = t2.UID AND
t1.created_at = t2.max_created_at;
Translating this over to Eloquent would be some work, but hopefully this gives you a good starting point.
Edit: You may want to use a LEFT JOIN if you expect that created_at could ever be NULL and that a given UID might only have null created values.
You can use a self join to pick latest row for each UID
select t.*
from yourTable t
left join yourTable t1 on t.uid = t1.uid
and t.created_at < t1.created_at
where t1.uid is null
Using laravel's query builder it would be similar to
DB::table('yourTable as t')
->select('t.*')
->leftJoin('yourTable as t1', function ($join) {
$join->on('t.uid','=','t1.uid')
->where('t.created_at', '<', 't1.created_at');
})
->whereNull('t1.uid')
->get();
Laravel Eloquent select all rows with max created_at
Laravel Eloquent group by most recent record
SELECT p1.* FROM product p1, product p2 where p1.CREATED_AT> p2.CREATED_AT group by p2.UID
You can achieve this with eloquent using orderBy() and groupBy():
$data = TblModel::orderBy('id','DESC')->groupBy('uid')->get();
SOLVED
Thanks to Tim and M Khalid for their replies. It took me down the right road but I hit a snag, hence why I am posting this solution.
This worked:
$allRowsNeeded = DB::table("table as s")
->select('s.*')
->leftJoin("table as s1", function ($join) {
$join->on('s.uid', '=', 's1.uid');
$join->on('s.created_at', '<', 's1.created_at');
})
->whereNull('s1.uid')
->get();
However I got an Access Violation so I had to go in to config/database.php and set
'strict' => false,
inside the 'mysql' config, which removes ONLY_FULL_GROUP_BY from the SQL_MODE.
Thanks again.
You have to use ORDER BY, and LIMITSQL parameters, which will lead you to an easy SQL request :
for exemple, in SQL you should have something like this :
SELECT *
FROM table_name
ORDER BY `created_at` desc
LIMIT 1
This will returns everything in the table. The results will be ordering by the column "created_at" descending. So the first result will be what you're looking for. Then the "LIMIT" tells to return only the first result, so you won't have all your database.
If you wanna make it with eloquent, here is the code doing the same thing :
$model = new Model;
$model->select('*')->orderBy('created_at')->first();

Inner Join in laravel missing P

I needed to combine the two table product_price and trade_channels, when I use inner join,
the ID of product_price is remove.
Here is my code
DB::table('product_price')->where('product_id',$id)->where('action','customer_price')
->join('customers','product_price.action_id','=','customers.id')
->get();
A good practise is to select a column that you actually want to use no need of all columns.
Suppose in this case you require all column of product_price table and only customer id from customer_price table then you can do something like this:
DB::table('product_price')
->select(['product_price.*','customer_price.id AS customer_id'])
->where('product_price.product_id',$id)
->where('product_price.action','customer_price')
->join('customers','product_price.action_id','=','customers.id')
->get();
You can select any column but it's good to take alias of join table column in this case it is customer_price so it's not getting confusion if both table has same name column.
Good Luck
try
DB::table('product_price')
->select('*','product_price.id AS product_price_id')
->where('product_id',$id)
->where('action','customer_price')
->join('customers','product_price.action_id','=','customers.id')
->get();
the product_price id would be replace with customers id, so just print out the product_price id with other name.
hope it is help

ORA-00904: invalid column name but I am using the correct column name

Can someone see where I am going wrong in the below query? I am getting the error message that the GROUP BY column doesn't exist, but it clearly does as I see that column name in the output when I don't use the GROUP BY.
SELECT
(SELECT customer_address.post_code FROM customer_address WHERE customer_address.address_type = 0 AND customer_address.customer_no = orders.customer_no) postcode, SUM(orders.order_no) orders
FROM
orders, customer_address
WHERE
orders.delivery_date = '27-MAY-15'
GROUP BY
postcode;
The answer is: You cannot use an alias name in GROUP BY.
So:
GROUP BY (SELECT customer_address.post_code ...);
Or:
select postcode, sum(order_no)
from
(
SELECT
(SELECT customer_address.post_code FROM customer_address WHERE customer_address.address_type = 0 AND customer_address.customer_no = orders.customer_no) postcode,
orders.order_no
FROM orders, customer_address
WHERE orders.delivery_date = '27-MAY-15'
)
GROUP BY postcode;
EDIT:
However, your query seems wrong. Why do you cross-join orders and customer_address? By mistake I guess. Use explicit joins (INNER JOIN customer_address ON ...), when using joins to avoid such errors. But here I guess you'd just have to remove , customer_address.
Then why do you add order numbers? That doesn't seem to make sense.

Calculating age/tenure in HiveQL

I'm using the below code to calculate tenure/customer age using datediff
select user_id, datediff('2014-09-30', to_date(date_joined)) as tenure_days
from users_table
group by user_id
Error
Error: Invalid column reference date_joined
Any help here would be highly appreciated!
There is no need for grouping here. Try bellow:
select distinct user_id, datediff('2014-09-30', to_date(date_joined)) as tenure_days
from users_table

Why is "group by" giving only one column as output?

I have a table something like this:
ID|Value
01|1
02|4
03|12
01|5
02|14
03|22
01|9
02|32
02|62
01|13
03|92
I want to know how much progress have each id made (from initial or minimal value)
so in sybase I can type:
select ID, (value-min(value)) from table group by id;
ID|Value
01|0
01|4
01|8
01|12
02|0
02|10
02|28
02|58
03|0
03|10
03|80
But monetdb does not support this (I am not sure may be cz it uses SQL'99).
Group by only gives one column or may be average of other values but not the desired result.
Are there any alternative to group by in monetdb?
You can achieve this with a self join. The idea is that you build a subselect that gives you the minimum value for each id, and then join that to the original table by id.
SELECT a.id, a.value-b.min_value
FROM "table" a INNER JOIN
(SELECT id, MIN(value) AS min_value FROM "table" GROUP BY id) AS b
ON a.id = b.id;

Resources