Im having a hard time working out a proper DQL to generate cumulative sum. I can do it in plain SQL but when it comes to DQL i cant get hold of it.
Here is how it looks in SQL:
SELECT s.name, p.date_short, p.nettobuy,
(select sum(pp.nettobuy) as sum from price pp where pp.stock_id = p.stock_id and p.broker_id = pp.broker_id and pp.date_short <= p.date_short) as cumulative_sum
FROM price p
left join stock s on p.stock_id = s.id
group by p.stock_id, p.date_short
order by p.stock_id, p.date_short
Thanks
Hey, I have check the documentation for Doctrine 1.2, and the way to create the query is (put attention on the alias):
$query = Doctrine_Query::create();
$query->addSelect('AVG(price) as price');
$query->addSelect('AVG(cost) as cost');
// as many addSelect() as you need
$query->from('my_table');
To output the SQL query created:
echo $query->getSqlQuery();
To execute the statement:
$product = $query->fetchOne();
And to access the retrieved data is:
echo $product->getPrice();
echo $product->getCost();
Read the rest of the documentation at Group By Clauses.
You just specify the sum in your select part of the DQL:
$query = Doctrine_Query::create()
->select('sum(amount)')
->from('some_table');
Check out this page in the Doctrine documentation for more info.
Related
I know this is a poorly written query. How can I re-write this using the Laravel Query builder?
SELECT tgi.rate, tgi.tax_types_id, tt.name, tt.sales_chart_master_id, tt.purchase_chart_master_id
FROM tax_group_items tgi, tax_types tt
WHERE tgi.tax_groups_id = (SELECT tax_groups_id FROM customers WHERE id=2)
AND tt.id = tgi.tax_types_id
AND tt.id NOT IN (SELECT tax_types_id FROM item_tax_type_exemptions WHERE item_tax_types_id = (SELECT item_tax_types_id FROM products WHERE id = 1))
The answer would be more easier and clearer to you if you post your relationships in the model class. If you dont know how to define relations, go to query builder section of official doc.
If you don't want to define relations or don't want to use them then use this
$query = DB::select('your query');
DB::table(DB::raw('tax_group_items tgi, tax_types tt'))
->select(['tgi.rate', 'tgi.tax_types_id', 'tt.name', 'tt.sales_chart_master_id', 'tt.purchase_chart_master_id'])
->whereRaw('tgi.tax_groups_id = (SELECT tax_groups_id FROM customers WHERE id=2)')
->where('tt.id', 'tgi.tax_types_id')
->whereRaw('tt.id NOT IN (SELECT tax_types_id FROM item_tax_type_exemptions WHERE item_tax_types_id = (SELECT item_tax_types_id FROM products WHERE id = 1))')
->get();
I need to get the percentage of each possible values in the field column, over the total value of my table.
I found two way to get my result in SQL:
SELECT m.field, sum(m.value) * 100 / t.total
FROM my_table AS m
CROSS JOIN (
SELECT SUM(value) AS total FROM
WHERE year = 2000) t
WHERE m.year = 2000
GROUP BY m.field, t.total
And
SELECT m.field, sum(m.value) * 100 / (SELECT SUM(value) AS total FROM WHERE year = 2000)
FROM my_table AS m
WHERE m.year = 2000
GROUP BY m.field
But both are nested queries, and I don't know how to prepare statments with the Doctrine's QueryBuilder into a nested queries.
Is there a way to do it?
I have been trying to do so using querybuilder and DQL with no success. As it seems, DQL doesn't allow operations with subqueries in SELECT. What I've achieved so far:
$subQuery = $em->createQueryBuilder('m')
->select("SUM(m.value)")
->where("m.year = 2000")
->getDQL();
The following query works though doesn't calculate the percentage:
$query = $em->createQueryBuilder('f')
->select("f.field")
->addSelect(sprintf('(%s) AS total', $subQuery))
->addSelect('(SUM(f.value)*100) AS percentage')
->where("f.year = 2000")
->groupBy("f.field")
->getQuery()
->getResult();
However, if you try to add the division in the select in order to get the percentage and you use the subquery, it simply doesn't work. Looks like the construction it's not allowed in DQL. I've tried with an alias and with the subquery directly and neither of them worked.
Doesn't work:
$query = $em->createQueryBuilder('f')
->select("f.field")
->addSelect(sprintf('(%s) AS total', $subQuery))
->addSelect('(SUM(f.value)*100)/total AS percentage')
->where("f.year = 2000")
->groupBy("f.field")
->getQuery()
->getResult();
Doesn't work either:
$query = $em->createQueryBuilder('f')
->select("f.field")
->addSelect(sprintf('(SUM(f.value)*100)/(%s) AS percentage', $subQuery))
->where("f.year = 2000")
->groupBy("f.field")
->getQuery()
->getResult();
I'd suggest using SQL directly (Doctrine allows it). Using native sql queries and mapping the results would do the trick. There is no disadvantage in doing so.
Documentation
If you find a way of doing it using queryBuilder or DQL, please let me know.
Hope it helps.
yeah! the solution is:
$qs = $this
->createQueryBuilder('h');
$d = $qs ->select($qs->expr()->count('h'));
$e = $d->getQuery()->getScalarResult();
$qs->addSelect('(COUNT(h.id)*100 / :t) AS percentage')->setParameter('t', $e);
$qs->addGroupBy(sprintf('h.%s', $type));
return $qs->getQuery()->getResult();
I don't know if these are "complex queries" by defn, but they look very complex to a noob like me.
So I have a query here that will get the latest chart of customer_id=5:
$query = "SELECT c.Chart_ID, c.Chart_Notes
FROM tblchart AS c WHERE c.Customer_ID=5
ORDER BY c.Last_Edited ASC LIMIT 1";
But I have to relate it to another table that uses the Chart_ID as foreign key. How can I get the data from the tblcontent using tblchart.Chart_ID=tblcontent.Chart_ID? I couldn't just add that as:
$query = "SELECT c.Chart_ID, c.Chart_Notes, d.Content_Desc, d.Content_Title
FROM tblchart AS c, tblcontent AS d
WHERE c.Customer_ID=5 AND c.Chart_ID=d.Chart_ID
ORDER BY c.Last_Edited DESC LIMIT 1";
can I? As that would limit the search to just one...the use of LIMIT 1 is just to get the latest, but for the subsequent query (extended query), I am expecting multiple results extracted from tblcontent in addition to the first query I posted. A join, maybe, or union, or a complex query, but how? Please, can anyone help me? Thanks.
SELECT a.Chart_ID, a.Chart_Notes, c.Content_Desc, c.Content_Title
FROM tblChart a
INNER JOIN
(
SELECT Chart_ID, MAX(Last_edited) maxEdited
FROM tblChart
GROUP BY Chart_ID
) b ON a.Chart_ID = b.Chart_ID AND
a.Last_Edited = b.maxEdited
INNER JOIN tblcontent c
ON a.Chart_ID = c.Chart_ID
WHERE a.Customer_ID=5
The following code is used in a query for fetching records. It uses the electors.ID to find the corresponding voting_intention.elector from a second table.
$criteria = "FROM voting_intention,electors WHERE voting_intention.elector = electors.ID AND voting_intention.pledge IN ('C','P') AND electors.postal_vote = 1 AND electors.telephone > 0"
The problem is that some electors will have more than one pledge in the voting_intentions table.
I need it to match only on the latest voting_intention.pledge based on the field votin_intention.date for each elector.
What is the simplest way of implementing that.
The rest of the code:
function get_elector_phone($criteria){
$the_elector = mysql_query("SELECT * $criteria ORDER BY electors.ID ASC"); while($row = mysql_fetch_array($the_elector)) {
echo $row['ID'].','; }
}
You could use a sub-select with the MAX() function. Add the following into your WHERE clause.
AND voting_intention.date = (select MAX(date)
from voting_intention vote2
where voting_intention.elector = vote2.elector)
Here is a SQLFiddle of the results.
So pretty much, you only want to bother looking at the most recent row that fits the first two criteria in your code. In that case, you would want to filter out the voting_intention table beforehand to only have to worry about the most recent entries of each. There's a question/answer that shows how do do that here.
Try selecting the following instead of voting_intention (from the answer of the linked question, some table and field names replaced):
SELECT voting_intention.*
FROM voting_intention
INNER JOIN
(
SELECT elector, MAX(date) AS MaxDate
FROM voting_intention
GROUP BY elector
) groupedintention ON voting_intention.elector = groupedintention.elector
AND voting_intention.date = groupedintention .MaxDate
Question url: How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?
Solution:
$query = $this->db->query("
SELECT *, SUM(views.times) AS sum
FROM channel
RIGHT JOIN video
ON channel.channel_id = video.channel_id
LEFT JOIN user
ON channel.user_id = user.user_id
LEFT JOIN views
ON channel.channel_id = views.channel_id
GROUP BY channel.channel_name
ORDER BY sum DESC
");
I have a query that returns a list of items.
function getfrontpage(){
$this->db->select('*');
$this->db->from('channel');
$this->db->join('video', 'channel.channel_id = video.channel_id' , 'right');
$this->db->join('user', 'channel.user_id = user.user_id');
$this->db->group_by("channel.channel_name");
$query = $this->db->get();
return $query->result();
}
Now i'm trying to order these with the SUM from another table, how can i achieve this?
Here is a picture from that table:
I want the results to be sorted by the SUM of the total of "times" for each "channel_id"
thanks in advance
I would suggest to run this through $this->db->query() instead.
It's nice to fetch simple values through CodeIgniters AR functions. But at some situations it's simply easier to build query strings instead.
In your case:
$query = $this->db->query("
SELECT channel_id, SUM(times) AS sum
FROM channel
GROUP BY channel_id
ORDER BY sum DESC
");
You can also escape most values through db->query()!
$this->db->query("
SELECT name
FROM table_name
WHERE id = ?
", array(1));
Isn't it as simple as $this->db->order_by("channel_id", "desc");? this orders the results by channel_id in descending order.
Assuming the table displayed in your question is called times_table, and has a key of user_id, channel_id, you can use the following code to join the times_table into your query so the "times" column is available to sort by.
$this->db->join("times_table", "times.user_id=channel.user_id, times.channel_id=channel.channel_id", "left");
// You've already grouped by channel_name, so grouping by channel_id is probably not necessary.
$this->db->order_by("SUM(times_table.times) DESC");
N.B. I just guessed the name of your displayed table is times_table.