I have a record in my database which looks like the below
Table
id client_id to_pay due session
1 12 100 50 ***
2 24 80 30 ***
3 12 0 10 ***
4 24 0 5 ***
Now in my query below, i want to fetch all data from the table above by grouping the data according to the client_id but in the query also, i need to sum up to_pay and due for each client in the response.
How do i get this done please ?
Controller
public function collectionPost(Request $request)
{
$fees = Collection::select('*')
->where('session',$request->get('session'))->groupby('client_id')->sum('due')
->get();
return $fees;
}
When you use the method sum it overwrites the select to get the right result.
You can build your select without using the sum method.
$fees = Collection::select(DB::raw('SUM(due) as total_due'), DB::raw('SUM(to_pay) as total_to_pay'))
->where('session',$request->get('session'))->groupby('client_id')
->get();
return $fees;
And add more to your select.
Related
following code is about getting the products from my db table using codeigniter sql queries.i am getting products of a row by limiting up to 4 products and by applying where condition of products less than cost of 900 but i am not getting how to get the products less than 900 but with different prices in each item. this means if once product 0f 500 is fetched it should not fetch 500 again it should go for another product by the help of product_id DESC. Explain me the logic of query how i should write
public function byPrice()
{
$query = $this->db->limit(4)
->where('pro_cost<', 900)
->get('products');
return $query;
}
$Q="SELECT DISTINCT `pro_cost` FROM `products` WHERE `pro_cost` < 900";
$result=$this->db->query($Q)->result();
$this->db->where('cost < 900', NULL)->group_by('id')->group_by('cost')->get('product')
I'm trying to get the sum of two different columns using Laravel query builder, the plain SQL Query below works just fine, but I can't get it to work with the Laravel Query.
SELECT SUM(logins_sun + logins_mon) FROM users_stats WHERE id = 7; // returns: 1034
Here's what I have tried.
$stats = DB::table('users_stats')->where('id', '=', '7')->sum('logins_sun', '+', 'logins_mon'); // returns: 587.0
And here is my DB structure.
+----+------------+------------+
| id | logins_sun | logins_mon |
+----+------------+------------+
| 7 | 587 | 447 |
+----+------------+------------+
It was supposed to return 1034 but the Laravel Query is returning only the last value 587.0 .
How can I get it working?
You can try with the sum() method like:
DB::table('users_stats')
->where('id', '7')
->sum(\DB::raw('logins_sun + logins_mon'));
sum is an aggregate function and only takes one argument. It will sum the values of each row in a column. In your case, the query only returns one row, so the sum is just the value of that one column (the first argument passed to sum()). There may be some better way to do it, but I think you should be able to use a raw expression to return the sum of the two columns.
$stats = DB::table('users_stats')
->select(DB::raw('logins_sun + logins_mon'))
->where('id', '=', '7');
Try passing a callback to the sum() and do the addition there like:
$stats = DB::table('users_stats')->where('id', '=', '7')->sum(function ($row) {
return $row->logins_sun + $row->logins_mon;
});
You can run direct raw sql in laravel with the following way :
$sql = "SELECT SUM(logins_sun + logins_mon) FROM users_stats WHERE id = :ID";
$result = DB::select($sql,['ID'=>7]);
I want to get 3 random records from my table to 90 times.
Scenario
user_id number_of_bids
12 20
8 40
6 30
what i want is...Get above 3 rows in random order to a specific number In fact it is sum(number_of_bids)...
And every row should not repeated greater than its number of bids..
I have created a query where I am getting sum of number_of_bids.Now second query required where these 3 records should be in random order to sum(number_of_bids) times and every record should not greater repeated greater than its number_of_bids.
Not sure it can be achieved in one query or not.But you people are experts I am sure you can help me.It will save my execution time..
Thanks..
I would just build an array out of the rows and shuffle it:
$stmt = $db->query('SELECT user_id, number_of_bids FROM table_name', PDO::FETCH_KEY_PAIR);
$results = array(); $startIndex = 0;
foreach ($stmt as $userId => $numberOfBids) {
$results += array_fill($startIndex, $numberOfBids, $userId);
$startIndex += $numberOfBids;
}
shuffle($results);
Then, you can iterate $results however you'd like.
I want to get the last 5 items of my search action. An example:
$quizzes = $user->getQuizs();
Now I would like to select the last 5 of that, is this possible with propel?
I tried ->getLast(5) but that's not correct.
Let's say I get 30 quizzes back, ordered by ID. I want to select the last 5 (with the highest id's .., these are the ones last created).
Easy peasy:
$quizzes = QuizQuery::create()->
filterByUser($user)->
orderByCreatedAt(\Criteria::DESC)->
limit(5)->
find()
;
This assumes you have a created_at column in your quiz table. You can then add this to your User model if you wish:
public function getLastQuizzes($limit = 5)
{
return QuizQuery::create()->
filterByUser($this)->
orderByCreatedAt(\Criteria::DESC)->
limit($limit)->
find()
;
}
Well guys i have this query
$mysql = "select * from xxx where active = 1 order by Rand() limit $start,12";
mysql_query($mysql);
Everything works great so far.
I want: when i am pressing the next button (page 2 or three etc) to see the next 12 random records but do not display the first 12 random records that i had in my previus page!
Thank you all!
p.s Sorry guys for my bad english!
Just try to retrieve the data you need in an array, randomize it with shuffle() in PHP, and paginate the result with some JQuery, it will be awesome, just one query and no refresh. ;)
You need to keep one array (e.g $arrRecordIds) to track all the id's of records shown on previous pages.
When you are on first page:
$arrRecordIds=array(); // Empty array
When you are on second page:
$arrRecordIds=array_merge($arrRecordIds, $arrNewRecordIds);array_unique( $arrRecordIds );
If your select query simply concat- where id NOT IN ( implode(',', $arrRecordIds ) )
Here $arrNewRecordIds should contains id's of the records on the page.
You can keep track of the previously shown records' ids and put them in an array.
In your query use id NOT IN (array)
Apply the concept of Systematic Random Sampling,
Number the records N, decide on the n (pagination size, eg: 10, 20)
(sample size) that you want or need k = N/n = the interval size
Randomly select an integer between 1 to k then take every k th unit
Refer: http://www.socialresearchmethods.net/kb/sampprob.php
Try using the following script in your showdata.php file
$per_page = 12;
$sqlc = "show columns from coupons";
$rsdc = mysql_query($sqlc);
$cols = mysql_num_rows($rsdc);
$page = $_REQUEST['page'];
$start = ($page-1)*12;
$N = 1000; //Total rows in your table (query to get it dynamically)
$n = $per_page;
$k = ceil($N/$n);
$range[] = $page;
for($i=1;$i<$n;$i++) {
$range[] = ($page+$k)*$i;
}
$sqln = "SELECT * FROM ( SELECT #rownum:= #rownum+1 AS rindex, n.* FROM xxx n, (SELECT #rownum := 0) r ) AS rows WHERE rindex IN (".implode(',',$range).")";
$rsd = mysql_query($sqln);
SOLUTION - that works a treat.
do a select random search of all required records
generate a random user-id eg. "smith".rand(1000,10000)
form a string of all random keys upto required no of records per page
insert above in a table/field containing a corresponding page no.
repeat/loop above until no more pages/recs remaining - use array_splice(str,from,to) - then use $notscreen = print_r($splice, true) for string storage to table -> randompages:
tb.rec-no | user-id | pageno | string ( with keys of recs upto recs/page)
122 | aj7894 | p1 | [0]=>100[1]=>400[2]=>056[3]=>129
123 | aj7894 | p2 | [x]99=>[x]240=>[x]7895[x]458=>320
... upto whole array of pages /no of records / all pages - no duplication of data - only 1-column of key of recs stored in random as retrieved
use user-id & pageno with WHERE to pull out random keys for that individual user & page
convert string back to array and pull out matching key recs for specific pages using the array in a SELECT WHERE query with implode
re-circ [ user-id & pageno ] using $_GET/POST for duration of search/view - reinitialise when new view or new search commences
notes:
-better to use list for search - but requires more work to format string - should give random page results as originally stored
problem with array matching is it orders records per page; lowest being first - not so random for the page display
temp table no good - because cannot be accessed when script is thrown back to server for 2nd and more time - it's lost from memory by mysql
php rules - no flimsy cookies or java-script !
BIG PROBLEM - SOLVED.
re-compsense for help received from your posts / answers.
Happy Days!