Count number of rows with distinct column - mysql

I'm trying to count the number of rows with a distinct column with Active Record.
The following SQL works and gives me the correct result:
SELECT COUNT(DISTINCT(user_id)) FROM attempts WHERE score = 100 AND problem_id = 1
But this code throws an ActiveRecord::StatementInvalid error:
attempts.where(:score => 100).count(:distinct => :user_id)

Try:
attempts.count('user_id', :conditions => "score = 100", :distinct => true)
more infos: http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html

Related

mysql - select result of two conditionals for the same table in one query

I am struggling to get correct results with this. I want to test if both, or either, exist. In results table, 'michael' exists while 'mike' does not.
$stmt = $dbnet->prepare("
SELECT * FROM
(SELECT cats AS cats1 FROM results WHERE name = :original) AS a,
(SELECT cats AS cats2 FROM results WHERE name = :parsed) AS b
");
$binding = array(
'original' => 'michael',
'parsed' => 'mike'
);
$stmt->execute($binding);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//if there was a result then output
if($results)
{
echo '<pre>'.print_r($results,1).'</pre>';
}
I get no results with this even though 'michael' is in the database.
If I test for 'original' => 'michael', 'parsed' => 'michael' I get results...both the same of course since I tested the same value for each :
Array
(
[0] => Array
(
[cats1] => 6,11
[cats2] => 6,11
)
)
What I expect is one of the following :
no results meaning neither michael or mike exist
result for cats1 and empty for cats2 (michael exists mike does not)
empty for cats1 and result for cats2 (mike exists michael does not)
No, I cannot use WHERE name = 'michael' OR name = 'mike' because what I do after changes depending if both have results or just one or the other.
This is working as epxected... both always needs a result even if that is empty to return correctly.
$stmt = $dbnet->prepare("
SELECT
IFNULL( (SELECT cats AS cats1 FROM results WHERE name = :original), '') AS a,
IFNULL( (SELECT cats AS cats2 FROM results WHERE name = :parsed), '') AS b
");

mysql - multiple rows from two tables and multiple values from one of second table column

$userid = 1; // got from session
select tableone.userid, tableone.name, tabletwo.action as action
from tableone
leftjoin tabletwo
where tabletwo.userid = $userid
on tableone.jailid = tabletwo.jailid
it returns all from tableone and all from tabletwo but the problem is one of the columns of table two i.e. action returns only one however in tabletwo there are more than one rows that matches the condition(tabletwo.userid = $userid on tableone.jailid = tabletwo.jailid).
it returns:
userid => 23
name => test title
action => 65
userid => 24
name => test title2
action => 65
i want:
userid => 23
name => test title
action => [65, 66, 67]
userid => 24
name => test title2
action => [76, 57, 34]
How can I fix this?
You can use GROUP BY with GROUP_CONCAT, e.g.:
SELECT tableone.userid, tableone.name, GROUP_CONCAT(tabletwo.action) AS action
FROM tableone
LEFT JOIN tabletwo
ON tableone.jailid = tabletwo.jailid
WHERE tabletwo.userid = $userid
GROUP BY tableone.userid, tableone.name;
Here's the documentation for GROUP_CONCAT function.

Operand should contain 1 column(s) ruby on rails

I have 3 model Shop Section and Price, Section have shop_id and Price have section_id
How can i show prices in Shop view?
controller/shop_controller.rb
...
def show
#metod_one = Magazine.find(params[:id])
#method_two = Section.find(:all, :conditions => ['shop_id = ?', #method_one])
#method_three = Price.find(:id, :conditions => ['section_id = ?', #method_two])
end
...
This method don't work
Mysql::Error: Operand should contain 1 column(s): SELECT * FROM prices WHERE (prices.id = '--- :id\n' AND (section_id = 5480,5482,5483,5485))
Please try the in operator:
#method_three = Price.find(:all, :conditions => ['section_id in (?)', #method_two])

an SQL query in LINQ

I have a table with these columns: CombinationID, IndexID, Value
There is a sql query:
SELECT CombinationID
FROM CombinationIndex
where IndexID <> 4
group by CombinationID
order by sum(case indexid when 1 then -Value else Value end) desc
How could I write this query in c# by linq?
I think this should just about do it for you (it's all off the top of my head so there could be slight syntactical errors):
var results = context
.CombinationIndexes
.Where(i => i.IndexID != 4)
.GroupBy(i => i.CombinationID)
.OrderBy(g => g.Sum(i => i.IndexID == 1 ? -i.Value : i.Value))
.Select(g => g.Key);

Alternative as NOT IN gives a blank array

I have a query in my rails application,
user_info = Information.where("user_id = ? and department_id NOT IN (?)",user.id, Department.unapproved_departments ).all(:include => [:name, :project]).
Here unapproved_departments contains an array of ids in Department table.
The problem arises when unapproved_departments is a blank array.In those cases "NOT IN"
checks for ids present in the array and entire user_info is returned as a blank array.
So i would like to have all the data with ids other than those in unapproved_departments array or you can say an alternative for NOT IN
Thanx
Theres nothing wrong with NOT IN -- just that you don't want it to fire when there's nothing there.
I suggest:
user_info = Information.where("user_id = ?", user)
unapproved_departments = Department.unapproved_departments
if unapproved_departments.present? # true if not blank or nil
user_info = user_info.where("department_id NOT IN (?)", unaproved_departments)
end
user_info.all(:include => [:name, :project])
As you can see, you can chain the conditions together.
Can't you just have a special case for when unapproved_departments is empty?
if Department.unapproved_departments.empty?
user_info = Information.where("user_id = ?",user.id).all(:include => [:name, :project])
else
user_info = Information.where("user_id = ? and department_id NOT IN (?)",user.id, Department.unapproved_departments ).all(:include => [:name, :project])
end
it will be better if you define better unapproved_departments to retun [nil] instead of []
Oterwhise you can add [0] to your code :
user_info = Information.where("user_id = ? and department_id NOT IN (?)",user.id, (Department.unapproved_departments << 0) ).all(:include => [:name, :project]).
If we concentrate just on the "NOT IN" part:
user_info = Information.where("department_id NOT IN (?)", []).to_sql
# => SELECT `informations`.* from `informations` where department_id not in (NULL)
Which is weird because of null-tests: http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html
What we can do is reverse the test and get the required result:
user_info = Information.where("NOT (department_id IN (?))", []).to_sql
# => SELECT `informations`.* from `informations` where NOT (department_id in (NULL))
It works because in MySQL everything is != NULL (and also < NULL and > NULL at same time!).