I have a database the tells each systems current and new model. (Each row has a system name, current model, and new model) I need to group the results by the current model and new model. So if the current and new model are the same i want one result. I got that to work but i also need to know how many systems are in each group. How can I do that? Im using CI
This is my query
$query2 = $this->db->query('SELECT * FROM rollout_systems WHERE scope_ID = '.$id.' GROUP BY EAM_Model, new_Model');
(EAM_Model = current model)
Don't know if i clarified enough. I need to be able to display the Current System, the New System, and the number of systems in that group.
So if 3 rows have "blah" as there current system and "blahblah" as there new system, i want it to say
Current: Blah
New: Blah Blah
number of systems: 3
It doesn't make sense to do a select * and a group by in the same statement. The columns you group by need to be in your select but then you should have an aggregate function like count(*) in your select. I'm not sure I totally understand what you are trying to do, but I think you want something like:
SELECT EAM_Model, new_Model, count(*)
FROM rollout_systems
WHERE scope_ID = '.$id.'
GROUP BY EAM_Model, new_Model
If you just want the number of items, use SELECT EAM_Model, new_Model, COUNT(*) FROM ... etc. When you group a query, you normally want to be performing an aggregate like COUNT or SUM or else it doesn't make sense to be grouping the data.
$query2 = $this->db->query('SELECT count(*) FROM rollout_systems WHERE scope_ID = '.$id.' GROUP BY EAM_Model, new_Model');
Is it this you are asking for?
Related
I am trying to create a query using eloquent where I need to know the total points summed by id, username and session_id.
but the result I get is not correct.
my code
$query = DB::table('advisors')
->select('advisors.id','advisors.nombre_comercial','session_details.session_id',
DB::raw('SUM(session_details.spent_points + template_sales.price_points) AS suma_total'))
->join('consultancy_requests','advisors.id','=','consultancy_requests.advisor_id')
->whereBetween('consultancy_requests.created_at',[$from,$to])
->join('receipts','consultancy_requests.id','=','receipts.session_id')
->where('receipts.status',NULL)
->whereBetween('receipts.created_at',[$from,$to])
->join('session_details','consultancy_requests.consultancy_id','=','session_details.session_id')
->whereBetween('session_details.created_at',[$from,$to])
->join('template_sales','session_details.session_id','=','template_sales.session_id')
->whereBetween('template_sales.created_at',[$from,$to])
->groupBy('advisors.id','advisors.nombre_comercial','session_details.session_id')
->get();
code responses
session_details table
template_sales table
this is the correct answer i want to get.
There are a couple of mistakes in your query that I noticed. For instance you don't need to SUM (session_details.spent_points + template_sales.price_points) because this is already performing the addition.
Instead of pointing out all these, let's break your problem down into smaller pieces; when query seems complicated it would be a good idea to break it down for better understanding. There seems to be a couple of tables but I will base my answer on the two tables provided, and that should give you a starting point.
Essentially, what you want is,
Get the sum of spent_points per session_id; so you need to group by session_id and sum(spent_points)
$sumSpentPointsQuery = DB::table('session_details')
->select('session_id', DB::raw('SUM(spent_points) as sum_spent_points'))
->groupBy('session_id');
Get the sum of price_points per session_id; so you need to group by session_id and sum(price_points)
$sumPricePointsQuery = DB::table('template_sales')
->select('session_id', DB::raw('SUM(price_points) as sum_price_points'))
->groupBy('session_id');
Now we need to get the addition of sum_spent_points and sum_price_points. This time our tables would be the results we got from the sub queries. So we can work with Laravel's fromSub and joinSub to get the result we want.
DB::query()
->select('ssp.session_id as session_id', DB::raw('sum_spent_points + sum_price_points as suma_total') )
->fromSub($sumSpentPointsQuery, 'ssp')
->joinSub($sumPricePointsQuery, 'spp', function($join){
$join->on('ssp.session_id', '=', 'spp.session_id');
})->get();
This query should produce the sql that represents this:
select ssp.session_id as session_id, (sum_spent_points + sum_price_points) as suma_total
from
(select session_id, sum(spent_points) as sum_spent_points
from session_details group by session_id) ssp
inner join
(select session_id, sum(price_points) as sum_price_points
from template_sales group by session_id) spp
on ssp.session_id = spp.session_id ;
Hope this kicks you in the right direction.
What do I have to change to get different results from different names.The table should give me the debts of each of them, this is calculated by the amount and the price of the drink. Now it should show all the names with the corresponding invoice that happens after the select
%sql select name, sum(getraenk.preis*schulden.menge) schulden from schulden \
join person on (fk_person = person.id)\
join getraenk on (fk_getraenk = getraenk.id)\
where name like ("dani")
Edit: it should spend all the names with their debts, that is:
dani = 8.5
michael = 12.5
...
Just in case your problem is very simple, you should be able to see all names and values with an SQL that looks like this:
select name, getraenk.preis*schulden.menge schulden
from schulden
join person on (fk_person = person.id)
join getraenk on (fk_getraenk = getraenk.id)
Note that I removed the where clause... this was the part that limited it to one name.
You also don't need the sum clause here unless you are doing a group by
Have you considered simply using GROUP BY name at the end of this query?
https://www.w3schools.com/sql/sql_groupby.asp
This will give you the sum of total debt for all names in your table which sounds like the result you are looking for.
You're missing
GROUP BY name
in the query.
I'm learning SAP queries.
I want to get all the Measure documents from an equipement.
To do that, I use 3 tables :
EQUI, IMPTT, IMRG
The query works but I have all documents instead I only want to get the last one by Date. But I can't do that. I'm sure that I have to add a custom field, but I have tried but none of them works.
For example, my last code :
select min( IMRG~INVTS ) IMRG~RECDV
from IMRG inner join IMPTT on
IMRG~POINT = IMPTT~POINT into (INVTS, IMRGVAL)
where IMRG~POINT = IMPTT-POINT AND
IMPTT~MPOBJ = EQUI-OBJNR
and IMRG~CANCL = '' group by IMRG~MDOCM IMRG~RECDV.
ENDSELECT.
Thanks for your help.
You will need to get the date from IMRG, and the inverted timestamp field, so the MIN() of this will be the most recent - that looks correct.
However your GROUP BY looks wrong. You should be grouping on the IMPTT~POINT field so that you get one record per measurement point. Note that one Point IMPTT can have many measurements (IMRG), so something like this:
SELECT EQUI-OBJNR, IMPTT~POINT, MIN(IMRG~IMRC_INVTS)
...
GROUP BY EQUI-OBJNR, IMPTT~POINT
If I got you correctly, you are trying to get the freshest measurement of the equipment disregard of measurement point. So you can try this query, which is not so beautiful, but it just works.
SELECT objnr COUNT(*) MIN( invts )
FROM equi AS eq
JOIN imptt AS tt
ON tt~mpobj = eq~objnr
JOIN imrg AS ig
ON ig~point = tt~point
INTO (wa_objnr, count, wa_invts)
WHERE ig~cancl = ''
GROUP BY objnr.
SELECT SINGLE recdv FROM imrg JOIN imptt ON imptt~point = imrg~point INTO wa_imrgval WHERE invts = wa_invts AND imptt~mpobj = wa_objnr.
WRITE: / wa_objnr, count, wa_invts, wa_imrgval.
ENDSELECT.
I have the following query. What results is two coloums, oakid and max(count(rating)). What I want is to have two columns, but instead of actually having the max(count(rating)), I want the rating associated with the max(count(rating)). How can I modify my query to give me this?
select oakid,
(select max(count(rating))
from climbs, routes
where climbs.routename = routes.name
and climbs.climberid = oakid group by routes.rating)
as skill
from climbers;
For example, if I have ratings "hard, hard, easy, easy, easy, medium", the max(count(rating)) will show "3", since there are 3 "easy" ratings, but I want it to show "easy", not "3".
It sounds as though you want the statistical mode (most frequently occurring) rating for each oakid or climberid. Oracle has a handy function to do this for us called STATS_MODE:
SELECT c.climberid AS oakid, STATS_MODE(r.rating) AS skill
FROM climbs c
INNER JOIN routes r ON (c.routename = r.name)
GROUP BY c.climberid;
try the following:
select oakid,
(select rating
from climbs, routes
where climbs.routename = routes.name
and climbs.climberid = oakid
group by routes.rating
having max(count(rating)) = count(rating))
as skill
from climbers
I am currently working on a project using NHiberate as the DAL with .NET 2.0 and NHibernate 2.2.
Today I came to a point where I had to join a bunch of entities/collections to get what I want. That is fine.
What got me was that I do not want the query to return a list of objects of a certain entity type but rather the result would include various properties from different entities.
The following query is not what I am doing but it is kind of query that I am talking about here.
select order.id, sum(price.amount), count(item)
from Order as order
join order.lineItems as item
join item.product as product,
Catalog as catalog
join catalog.prices as price
where order.paid = false
and order.customer = :customer
and price.product = product
and catalog.effectiveDate < sysdate
and catalog.effectiveDate >= all (
select cat.effectiveDate
from Catalog as cat
where cat.effectiveDate < sysdate
)
group by order
having sum(price.amount) > :minAmount
order by sum(price.amount) desc
My question is, in this case what type result is supposed to be returned? It is certainly not of type Order, neither is of type LineItems.
Thanks for your help!
John
you can always use List of object[] for returning data and it will work fine.
This is called a projection, and it happens any time you specify an explicit select clause that contains rows from various tables (or even aggregate / summary data from a single table).
Using LINQ you can create anonymous objects to store these rows of data, like this:
var crunchies = (from foo in bar
where foo.baz == quux
select new { foo.corge, foo.grault }).ToList();
Then you can do crunchies[0].corge for example to pull out the rows & columns.
If you are using NHibernate.Linq this will "just work".
If you're using HQL or Criteria API, then what Fahad mentioned will work. You'll get a List<object[]> as a result, and the index of the array references the order of the columns that you returned in your select clause.