I have two table both are same in definition but different in records
one table is having todays date another table is having yesterday's data:--
TableA-- today's data
name,name_code,start_dt, subname,subname_code,subname_st_date
abc Active 12-04-1026 abc1 Active 13-042016
def Active 23-03-2016 def987 Active 23-01-2016
TableB -- yesterday's data
name,name_code,start_dt, subname,subname_code,subname_st_date
abc Inactive 12-04-1026 abc1 Active 13-042016
def Active 24-03-2016 def987 Inactive 23-01-2016
def Active 24-02-2016 def876 Inactive 23-01-12016
My requirement is to compare both the table and output should be the difference in records stated as below
For example:---
Subname were Cancelled : def987
New subname added : def876
Kindly help.
select coalesce(
case
when b.subname_code = 'Inactive'
then 'Subname were Cancelled :'
else 'New subname added :'
end
, b.subname)
from tableb b
left outer join tablea a on a.subname = b.subname
where a.subname_code <> b.subname_code or a.subname_code is null;
Related
This is a hard problem to describe but I have Rails query where I join another table and I want to exclude any results where the join table contain one of three conditions.
I have a Device model that relates to a CarUserRole model/record. In that CarUserRole record it will contain one of three :role - "owner", "monitor", "driver". I want to return any results where there is no related CarUserRole record where role: "owner". How would I do that?
This was my first attempt -
Device.joins(:car_user_roles).where('car_user_roles.role = ? OR car_user_roles.role = ? AND car_user_roles.role != ?', 'monitor', 'driver', 'owner')
Here is the sql -
"SELECT \"cars\".* FROM \"cars\" INNER JOIN \"car_user_roles\" ON \"car_user_roles\".\"car_id\" = \"cars\".\"id\" WHERE (car_user_roles.role = 'monitor' OR car_user_roles.role = 'driver' AND car_user_roles.role != 'owner')"
Update
I should mention that a device sometimes has multiple CarUserRole records. A device can have an "owner" and a "driver" CarUserRole. I should also note that they can only have one owner.
Anwser
I ended up going with #Reub's solution via our chat -
where(CarUserRole.where("car_user_roles.car_id = cars.id").where(role: 'owner').exists.not)
Since the car_user_roles table can have multiple records with the same car_id, an inner join can result in the join table having multiple rows for each row in the cars table. So, for a car that has 3 records in the car_user_roles table (monitor, owner and driver), there will be 3 records in the join table (each record having a different role). Your query will filter out the row where the role is owner, but it will match the other two, resulting in that car being returned as a result of your query even though it has a record with role as 'owner'.
Lets first try to form an sql query for the result that you want. We can then convert this into a Rails query.
SELECT * FROM cars WHERE NOT EXISTS (SELECT id FROM car_user_roles WHERE role='owner' AND car_id = cars.id);
The above is sufficient if you want devices which do not have any car_user_role with role as 'owner'. But this can also give you devices which have no corresponding record in car_user_roles. If you want to ensure that the device has at least one record in car_user_roles, you can add the following to the above query.
AND EXISTS (SELECT id FROM car_user_roles WHERE role IN ('monitor', 'driver') AND car_id = cars.id);
Now, we need to convert this into a Rails query.
Device.where(
CarUserRole.where("car_user_roles.car_id = cars.id").where(role: 'owner').exists.not
).where(
CarUserRole.where("car_user_roles.car_id = cars.id").where(role: ['monitor', 'driver']).exists
).all
You could also try the following if your Rails version supports exists?:
Device.joins(:car_user_roles).exists?(role: ['monitor', 'driver']).exists?(role: 'owner').not.select('cars.*').distinct
Select the distinct cars
SELECT DISTINCT (cars.*) FROM cars
Use a LEFT JOIN to pull in the car_user_roles
LEFT JOIN car_user_roles ON cars.id = car_user_roles.car_id
Select only the cars that DO NOT contain an 'owner' car_user_role
WHERE NOT EXISTS(SELECT NULL FROM car_user_roles WHERE cars.id = car_user_roles.car_id AND car_user_roles.role = 'owner')
Select only the cars that DO contain either a 'driver' or 'monitor' car_user_role
AND (car_user_roles.role IN ('driver','monitor'))
Put it all together:
SELECT DISTINCT (cars.*) FROM cars LEFT JOIN car_user_roles ON cars.id = car_user_roles.car_id WHERE NOT EXISTS(SELECT NULL FROM car_user_roles WHERE cars.id = car_user_roles.car_id AND car_user_roles.role = 'owner') AND (car_user_roles.role IN ('driver','monitor'));
Edit:
Execute the query directly from Rails and return only the found object IDs
ActiveRecord::Base.connection.execute(sql).collect { |x| x['id'] }
In Rails 3, how do i select rows based on unique column values, i need to get all the columns for eg:
SELECT COUNT(DISTINCT date) FROM records
This only returns date column, but i want all the columns (name, date , age , created_at) columns not just the date.
Thanks for your help
The issue here is that, by definition, there may be multiple records with the same date. It requires logic in the user space to determine which of the multiple records with the unique date to use. Here's some code to get those rows:
Record.select("distinct date").each do |record|
records = Record.find_by_date record.date
puts records.count # do something with the records
end
If what you're really after is uniqueness among multiple columns, list all the relevant columns in the distinct query:
Record.select("distinct date, name, age, created_at").each do |record|
puts record.date
puts record.name
puts record.age
puts record.created_at
# ``record'' still represents multiple possible records
end
The fact that you are using distinct means that each "row" returned actually represents n rows, so the DB doesn't know which of the n rows to pull the remaining columns from. That's why it only returns the columns used in distinct. It can do no other...
I think this will help you
Model.find(:all, :select => 'DISTINCT name, date, age, created_at')
Please use it and let me know.
Model.group(:column)
For your case:
Record.group(:date)
This will return all your columns with no "date" repetitions.
For rails 3.2 and higher, Model.select('DISTINCT name, date, age, created_at')
I am using ruby 1.8.6 , rails 2.3.8.
Here , I have a problem with multiple combo box in Rails,
Product drop down list
Sku's drop down list ( depends on production selection )
Product tables fields are
id name
In Sku's tables fields are
id name product_id alias_id
Alias tables fields are
id name
For example I have Sku's tables data like below
id name product_id alias_id
1. 100-m 1 10
2. 10-ml 1 NULL
3. 150 1 2
4. 200-m 1 10
5. 300-m 1 10
in Controller I written query like,
#skus = Sku.all(:conditions => ["product_id = ? ",
params[:id]],:select=>"skus.id,
CASE when skus.alias_id IS NOT NULL then (SELECT alias.name FROM alias WHERE
alias.id = skus.alias_id group by alias.name) END AS 'skus_name'",
:order=>"skus_name" ,:include=>[:alias])
This query written output like,
id skus_name
1. 100gms
2. 10-ml
3. 150-ml
4. 100gms
5. 100gms
Can any one help me how to get the distinct results?
Thanks in advance
You can either call uniq on the #sku variable that is returned.
#skus = Sku.all(:conditions => ["product_id = ? ",
params[:id]],:select=>"skus.id,
CASE when skus.alias_id IS NOT NULL then (SELECT alias.name FROM alias WHERE
alias.id = skus.alias_id group by alias.name) END AS 'skus_name'",
:order=>"skus_name" ,:include=>[:alias]).uniq
This will perform the same DB select but get unique results in ruby.
The alternative is to use DISTINCT in the select
#skus = Sku.all(:conditions => ["product_id = ? ",
params[:id]],:select=>"skus.id,
CASE when skus.alias_id IS NOT NULL then (SELECT DISTINCT alias.name FROM alias WHERE
alias.id = skus.alias_id group by alias.name) END AS 'skus_name'",
:order=>"skus_name" ,:include=>[:alias])
This will only get unique results in the database.
I'd go with the second option as it should be quicker than doing uniq in ruby :)
In two tables mapped to ActiveRecord with unknown number of identical columns, e.g.:
Table A Table B
--------- ---------
id id
name name
age email
email is_member
How can I (elegantly) copy all identical attributes from a record of Table A to a record of Table B, except the id attribute?
For the example tables above, name and email fields should be copied.
Try this:
Get intersection of the columns between TableA and TableB
columns = (TableA.column_names & TableB.column_names) - ["id"]
Now iterate through TableA rows and create the TableB rows.
TableB.create( TableA.all(:select => columns.join(",") ).map(&:attributes) )
Edit: Copying one record:
table_a_record = TableA.first(:select => columns.join(","), :conditions => [...])
TableB.create( table_a_record.attributes)
Migt consider using a union function on the acitverecord attributes hash between the 2 tables. It's not a complete answer but may help
Let's say I have an array of objects from the same class, with two attributes of concern here: name and created_at.
How do I find objects with the same name (considered dups) in the array, and then delete the duplicate record in the database. The object with the most-recent created_at date, however, is the one that must be deleted.
seen = []
#sort by created date and iterate
collection.sort({|a,b| a.created_at <=> b.created_at}).each do |obj|
if seen.map(&:name).include? obj.name #check if the name has been seen already
obj.destroy!
else
seen << obj #if not, add it to the seen array
end
end
Should do the job hopefully.
If this is just a one-time bugfix before introducing UNIQUE INDEX on the table, you might as well do it in SQL:
DELETE FROM t WHERE id IN (
SELECT t1.id
FROM t t1
LEFT JOIN t t2 ON t1.name = t2.name AND t2.created_at < t1.created_at
WHERE t2.id IS NOT NULL
)