How to write a select count group by SQL query in LINQ? - linq-to-sql

I have this query which works but when I try to write the equivalent in LINQ I get the incorrect SQL produced.
My query is:
SELECT COUNT(*)
FROM tableName
GROUP BY ColumnId
I've tried writing it as:
tableName.GroupBy(x => x.ColumnId).Count()
But looking in LINQPad it is producing the SQL:
SELECT COUNT(*) AS [value]
FROM (
SELECT NULL AS [EMPTY]
FROM [tableName] AS [t0]
GROUP BY [t0].[ColumnId]
) AS [t1]
What am I doing wrong? Thanks!

Your LINQ query is counting the number of groups but your SQL query is producing the counts by group. You want
var counts = tableName.GroupBy(x => x.ColumnId)
.Select(g => new { g.Key, Count = g.Count() });
to get the counts by group.
Note that if you want exactly the same SQL you want
var counts = tableName.GroupBy(x => x.ColumnId)
.Select(g => g.Count());
The first example above should be a little more useful as it gives the ids of each group as well.

Try tableName.GroupBy(x => x.ColumnId).Select(x => x.Count())

Related

How to use MAX function in yii2 query?

I have a query:
SELECT hs.*
FROM hire_screening hs
INNER JOIN
(SELECT resume_id, MAX(created_date) AS MaxDateTime
FROM hire_screening
GROUP BY resume_id) hire_screening
ON hs.resume_id = hire_screening.resume_id
AND hs.created_date = hire_screening.MaxDateTime
This is my table:
I need the answer like this:
I tried this:
$query = HireScreening::find()-
->select(["hire_screening.screening_id","hs.resume_id",
"MAX(hs.created_date) AS
MaxDateTime","hs.screening_by","hsl.screening_level as
hr_level","hss.screening_status as
hr_status","hr.candidate_name","hsm.screening_mode as
hr_mode","hire_screening.created_date","hs.screening_date"])
->innerJoin('hire_screening as hs','hs.resume_id =
hire_screening.resume_id')
->leftJoin('hire_screening_level as
hsl','hire_screening.screening_level = hsl.id')
->leftJoin('hire_screening_mode as
hsm','hire_screening.screening_mode = hsm.id')
->leftJoin('hire_screening_status as
hss','hire_screening.screening_status = hss.id')
->leftJoin('hire_resume as
hr','hire_screening.resume_id=hr.resume_id')
//->where(['hire_screening.created_date = MaxDateTime'])
->groupBy(['resume_id']);
//->having(['hire_screening.created_date' =>
'hs.MaxDateTime']);
$query->orderBy(['created_date' => SORT_DESC]);
But it didn't shows the answer. I need the distinct resume_id's with latest created date. The sql query shows the correct answer.I want to write this query in my search model. Please help me to convert this query into yii2.
If there is a table MyTable, then you can use simplier query grouping the table by resume_id:
SELECT
screening_id,
resume_id,
screening_by,
screening_date,
screening_level,
screening_mode,
screening_status,
reject_reason,
remarks,
created_by,
MAX(created_date) AS created_date
FROM MyTable
GROUP BY resume_id;
Using simplify query helps to avoid an errors. Also you could create a view or a stored procedure using the query and call this from your PHP code.

Zend 2 subquery columns

I want to create a SQL(MySQL) query in Zend Framework 2 like:
SELECT a.id,
a.name,
a.age,
(SELECT MAX(score)
FROM scores AS s
WHERE s.user_id = a.id) AS max_score,
(SELECT SUM(time)
FROM games_played_time AS gpt
WHERE gpt.user_id = a.id) AS time_played
FROM users AS a
ORDER BY last_visited DESC
LIMIT 0, 100
Mind that this is an artificial example of existing query.
I tried creating sub-queries and then creating main select query where when I use:
$select->columns(
array(
'id',
'name',
'age',
'max_score' => new Expression('?', array($sub1),
'time_played' => new Expression('?', array($sub2)
)
I also tried using:
$subquery = new \Zend\Db\Sql\Expression("({$sub->getSqlString()})")
And even lambda functions like suggested here: http://circlical.com/blog/2014/1/27/zend-framework-2-subqueries-subselect-and-table-gateway
Still no luck because all the time I keep getting errors like:
No data supplied for parameters in prepared statement
And when I succeed in making the query work, it ends up that column contains the text of sub-queries. It starts to look that it is not possible to make multiple expressions in columns method. Any ideas?
SOLVED:
I rewrote query by query as #Tim Klever proposed. Everythin worked except one query. It turns out there is some kind of issue when using limit in subquery and in main query. In my case one of the subqueries returns multiple rows, so I ussed limit(1) to force return of a single value. But using that turned out to produce error:
No data supplied for parameters in prepared statement
I changed the query to use MAX instead of limit and now it works. Later will try to debug why this is happening.. Thank you!
The following worked for me to produce the query you listed
$maxScoreSelect = new Select();
$maxScoreSelect->from(array('s' => 'scores'));
$maxScoreSelect->columns(array(new Expression('MAX(score)')));
$maxScoreSelect->where->addPredicates('s.user_id = a.id');
$sumTimeSelect = new Select();
$sumTimeSelect->from(array('gpt' => 'games_played_time'));
$sumTimeSelect->columns(array(new Expression('SUM(time)')));
$sumTimeSelect->where->addPredicates('gpt.user_id = a.id');
$select = new Select();
$select->from(array('a' => 'users'));
$select->columns(array(
'id',
'name',
'age',
'max_score' => new Expression('?', array($maxScoreSelect)),
'time_played' => new Expression('?', array($sumTimeSelect))
));
$select->order('last_visited DESC');
$select->limit(100);
$select->offset(0);

Find all distinct field values for a Model that occur N times in CakePHP

So I have a model FeaturedListing that has a field date which is a mysql date field. There will be multiple FeaturedListings that have the same date value.
I want to find all dates that have N or more FeaturedListings on it. I think I'd have to group by date and then find which ones have N or more in there group and get the value that was grouped on. Could any one give me any pointers to accomplish that. A raw sql query may be required.
Edit: Thanks to the answers below it got me going on the right track and I finally have a solution I like. This has some extra conditions specific to my application but I think its pretty clear. This snippet finds all dates after today that have at least N featured listings on them.
$dates = $this->find('list', array(
'fields' => array('FeaturedListing.date'),
'conditions' => array('FeaturedListing.date >' => date('Y-m-d') ),
'group' => array('FeaturedListing.date HAVING COUNT(*) >= $N')
)
);
I then make a call to array_values() to remove the index from the returned list and flatten it to an array of date strings.
$dates = array_values($dates);
No need to go to raw SQL, you can achieve this easily in cake ($n is the variable that holds N):
$featuredListings = $this->FeaturedListing->find('all', array(
'fields' => array('FeaturedListing.date'),
'group' => array('FeaturedListing.date HAVING COUNT(*)' => $n),
));
In "raw" SQL you would use group by and having:
select `date`
from FeaturedListings fl
group by `date`
having count(*) >= N;
If you want the listings on these dates, you need to join this back to the original data. Here is one method:
select fl.*
from FeaturedListings fl join
(select `date`
from FeaturedListings fl
group by `date`
having count(*) >= N
) fld
on fl.`date` = fld.`date`

How to pass data dynamically to mysql query

I have following query,
SELECT t_subject.subject, SUM( t_skilllist.skill_level ) AS total_skill, t_users.first_name,
t_skilllist.skill_level
FROM `t_skilllist`
JOIN t_subject ON t_subject.id = t_skilllist.subject_id
JOIN t_users ON t_users.id = t_skilllist.user_id
WHERE t_subject.subject = 'html'
GROUP BY t_users.first_name
ORDER BY total_skill DESC
LIMIT 0 , 30
I want to display subject and skill level for each student. But, for one subject I can do that with above query. As an example for html it works. However, I want to pass more than one subject to the query dynamically. I tried to combined subjects with AND operator but it return empty result set.
How to solve this? How to pass more than two subjects to the query? I am using PHP as server side scripting language.
You can use the IN() clause.
WHERE t_subject.subject IN ('html', 'php', 'and', 'a', 'lot', 'more')

Zend framework order before group

Any one have a example how to order before group with leftjoin in zend paginator adapter ?
new Zend_Paginator_Adapter_DbSelect($this->db->select()
->from(array( 'a' => $this->prefix.'contest' ), array('id'))
->joinLeft(array( 'b' => $this->prefix.'logo_to_contest'),'a.id=b.contest_id', array('img'))
->group('a.id')
->order('a.end','a.date_start DESC','b.id RAND()')
)
From mysql manuel
In general, clauses used must be given in exactly the order shown in
the syntax description. For example, a HAVING clause must come after
any GROUP BY clause and before any ORDER BY clause. The exception is
that the INTO clause can appear either as shown in the syntax
description or immediately following the select_expr list.
and in the syntax description group comes before order so it has nothing to do with zend
it's mysql that requires that you put group before order.
However to get around this issue and group after ordering you can select with a subquery with order then group on a new select like :
$subselect = $db->select()
->from(array( 'a' => $this->prefix.'contest' ), array('id'))
->joinLeft(array( 'b' => $this->prefix.'logo_to_contest'),'a.id=b.contest_id', array())
->order('a.end','a.date_start DESC','b.id RAND()');
$select = $db->select()->from(a(array( 'a' => $this->prefix.'contest' ), array('id'))
->joinLeft(array( 'b' => $this->prefix.'logo_to_contest'),'a.id=b.contest_id', array('img'))
->where("a.id in ($subselect)")
->group('a.id');