Hello I am trying to make a Select where the uses chooses department and would like to have clause WHERE this department is first, let's say we select 10 results from department: Taxes and then make a SUM SELECT of fee WHERE status = 1. Which results be selected based on the first select All the results are coming from the same table.
| id | department | status | fee |
----------------------------------
| 1 | tax | 1 | 20 |
| 2 | tax | 2 | 20 |
| 3 | tax | 1 | 20 |
| 4 | accounting | 1 | 20 |
So I would like to select if department is choose as tax, and status is 1 the sum of FEE columns which should be 40
So far my Select query looks like this:
SELECT P.id, P.fee, (SELECT SUM(P.fee) FROM cases P WHERE status = 1) as fee_USD
FROM cases P WHERE 1";
if (!empty($department)) { $sql .= " AND P.department = '$department'"; }
the last line is checking if department is given as select option. there are other options as well but to make it simple I have pasted only this part of it. Any help is welcome.
In the Current Selection Fee is = 80
You have to add correlation to your query:
SELECT P1.id, P1.fee,
(SELECT SUM(P2.fee)
FROM cases P2
WHERE P2.department = P1.department AND status = 1) as fee_USD
FROM cases P1
WHERE 1 ...
This way the subquery will return the SUM of only those records which are related to the current record of the main query.
Related
enter image description here I am having one table like id, sale_id, item_total, tax fields. need to sum the item_total by grouping the tax values.
Table 1
id | sale_id | item_cost_price | tax |
1 | 10 | 150 | 5 |
2 | 10 | 50 | 7 |
3 | 10 | 30 | 5 |
this is required output:
id | sale_id | item_cost_price | tax |
1 | 10 | 180 | 5 |
2 | 10 | 50 | 7 |
When i tried this query,
SELECT sale_id,tax FROM bgs_ib_sales_items GROUP BY tax
$query=$this->db->query("SELECT sale_id,tax FROM bgs_ib_sales_items GROUP BY tax ");
echo $num = $query->num_rows();
$result=array();
foreach($query->result() as $row){
$result_row[]=$row->sale_id;
$result_row[]=$row->tax;
$result_row[]=$row->item_cost_price;
}
My output is:
i am getting output like this,
am getting distinct tax only. but i need to sum item total values.
Note:
Image 1 : refer my datatable
Image 2: refer my expected outputenter image description here
Add SUM(item_cost_price) in SELECT statement.
In your select statement your select only sale_id, tax. But what you echo are sale_id, tax, and item_cost_price which not exist in your SELECT statement. Try This:-
$sql = "SELECT sale_id,tax, SUM(item_cost_price ) AS TotalPrice FROM bgs_ib_sales_items WHERE sale_id = '10' GROUP BY tax";
$query=$this->db->query($sql);
foreach($query->result() as $row){
$result_row[]=$row->sale_id;
$result_row[]=$row->tax;
$result_row[]=$row->TotalPrice;
}
Products :
--------------------------------------------
| ID | Group | Name | Sold |
--------------------------------------------
| 1 | A | Dell | 0 |
--------------------------------------------
| 2 | A | Dell | 0 |
--------------------------------------------
| 3 | B | Dell | 1 |
--------------------------------------------
| 4 | B | Dell | 1 |
--------------------------------------------
| 5 | C | Dell | 0 |
--------------------------------------------
| 6 | C | Dell | 1 |
--------------------------------------------
Hi everyone, i have a table (products) stored in MySql with many records, for now i'm using this query SELECT * FROM products WHERE sold = 0, in results i get :
--------------------------------------------
| ID | Group | Name | Sold |
--------------------------------------------
| 1 | A | Dell | 0 |
--------------------------------------------
| 2 | A | Dell | 0 |
--------------------------------------------
| 5 | C | Dell | 0 |
--------------------------------------------
i want to get only one record from each group, so the results will be like :
--------------------------------------------
| ID | Group | Name | Sold |
--------------------------------------------
| 1 | A | Dell | 0 |
--------------------------------------------
| 5 | C | Dell | 0 |
--------------------------------------------
You could easily do this by using a distinct clause and removing the id column. If you want to keep the id column you need to specify how one would chose which id to keep.
select distinct
`group`
, name
, sold
from
products
where
sold = 0;
To keep the row with the smallest id (as your example shows) something along the lines of the example below would work.
select
id
, `group`
, name
, sold
from
products
where
sold = 0
and id = (
select
min(p.id)
from
products p
where
p.`group` = products.`group`
and p.sold = 0
);
First, change your field named Group to something like Group_Name. GROUP is a reserved keyword, and if it is not causing you problems now it probably will later.
Second, you should ask yourself what you are really after. The following query should generate your desired result. It adds an additional condition where the IDs that are returned are the lowest numbered ID in each group.
SELECT * FROM products
WHERE sold = 0
AND ID IN (SELECT MIN(ID) FROM products WHERE sold = 0 GROUP BY Group_Name)
Why do you want that, though? That is not a normal desired end state. You should ask yourself why you care about the ID. It looks like your goal is to figure out which products have not sold anything. In that case, I would recommend this instead:
SELECT DISTINCT Group_Name, Name
FROM products
WHERE sold = 0
ORDER BY Group_Name, Name
I found the solution by using the statement GROUP BY,
SELECT * FROM products WHERE sold = 0 GROUP BY group
in the results now, i get only one record for each group and the minimal id without adding any other statement, and in my real table i am using product_group instead of group because it's a reserved word.
Try this:
SELECT `ID`, `Group`, `Name`, `Sold` FROM products WHERE sold = 0 GROUP BY `Group`;
How to query for erase the view below?
+-------------------+------------+
| Order_id | Weight |
| 20 | 4 |
| 21 | 5 |
| 22 | 2 |
| 22 | 2 |
+-------------------+------------+
To be like this:
+-------------------+------------+
| Order_id | Weight |
| 20 | 4 |
| 21 | 5 |
| 22 | 2 |
| 22 | |
+-------------------+------------+
When displaying results but not entered into the database.
A simple way is:
select DISTINCT order_id, weight from xyz
UNION
select order_id, null from xyz
group by order_id, weight
having count(*) > 1
Order by weight desc;
The 1st select statement will display all the unique values and 2nd one will retrieve only the repeated values.
In your required output table, it seems like you want to display all the non-repeated rows and the 1st column value of repeated rows but not 2nd column value. The above query will allow you to do that.
OK, here is how to do it:
SELECT
Order_id,
Weight,
if(#order_id = Order_id, '', Weight) as no_dup_weight,
#order_id := Order_id as dummy
FROM Table1
ORDER BY Order_id asc;
You basically need to check to see if the previous Order_id is the same as the current, and if they are, output an empty field.
Here is an SQLFiddle demonstrating the solution.
Do you actually need 2 rows for the dupes? Can't you just use the DISTINCT clause as per http://www.mysqltutorial.org/mysql-distinct.aspx
Or is it important to know what has duplicates. In which case you should look into the GROUP BY clause
I'm trying to figure out how to select 3 adjacent rows from a table with a price < current item price. The problem is that if I'm selecting the first, second, or third row in the table, I need to select three adjacent rows around the current item. Emphasis needs to be put on the lower price items, for example, if I'm selecting the third row from the table, I need to select the first two rows and the fourth row. Here is my query so far:
SELECT *
FROM (SELECT *
FROM temp_db_cart
WHERE airport='$airport'
AND people='$people'
AND price < '$price'
ORDER BY price DESC LIMIT 3
)
ORDER BY price ASC
Sample data:
+---------------+---------+--------+-------+
| hotel_name | airport | people | price |
+---------------+---------+--------+-------+
| Days Inn | MLB | 1 | 109 |
| Holiday Inn | MCO | 2 | 149 |
| Americas Best | MLB | 2 | 199 |
| Econo Lodge | SFB | 1 | 209 |
+---------------+---------+--------+-------+
Expected results:
Selected hotel: Americas Best
+---------------+-------+---------+--------+-------+
| hotel_name | order | airport | people | price |
+---------------+-------+---------+--------+-------+
| Days Inn | 1 | .. | .. | .. |
| Holiday Inn | 2 | .. | .. | .. |
| Americas Best | Skip | .. | .. | .. |
| Econo Lodge | 3 | .. | .. | .. |
+---------------+-------+---------+--------+-------+
PHP/MySQL combination can be used for an answer. Any help would be appreciated.
You can union the two records with lower prices with the record of higher price:
select * from
(
(SELECT *
FROM temp_db_cart
WHERE airport='MCO'
AND people='3'
AND price < '245'
ORDER BY price DESC LIMIT 3)
UNION
(SELECT *
FROM temp_db_cart
WHERE airport='MCO'
AND people='3'
AND price > '245'
ORDER BY price LIMIT 1)
)
order by price desc limit 3
In the first query, you select 3 rows and in the second, 1 row (if it exists). Finally, Out of these 3+1 (or 3+0) rows, you select only 3 rows with highest price.
SELECT *
FROM (SELECT MIN(price)
FROM temp_db_cart
WHERE airport='$airport'
AND people='$people'
AND hotel != '$hotel'
ORDER BY price DESC LIMIT 3
)
ORDER BY price ASC
After 2 hours, I finally found the solution. I combined a union with two select queries that selects 3 rows before (and including the selected hotel) and 3 rows after the selected hotel. I then set limit 3 and order by price asc and everything it mostly works.
SELECT *
FROM (
(
SELECT *
FROM temp_db_cart
WHERE price >= {$package['price']}
AND airport = '{$airport['abbr']}'
AND people = '{$travelers['number-of-travelers']}'
ORDER BY price ASC limit 3 )
UNION
(
SELECT *
FROM temp_db_cart
WHERE price < {$package['price']}
AND airport = '{$airport['abbr']}'
AND people = '{$travelers['number-of-travelers']}'
ORDER BY price DESC limit 3 ) ) AS u
WHERE hotel_name != '{$package['hotel_name']}'
ORDER BY price ASC limit 3;
Edit: The limiting of 3 rows in the parent select query only limits to the first 3 rows from the union set. How do I limit with an offset starting at 2 rows before the selected hotel and ending at 2 rows after the selected hotel of the union subset?
In a blog-like website, all the users can "star" a news (= bookmark it, mark it as "favourite").
I have a mysql table for stats.
table_news_stats
id_news
total_stars (int) //Total number of users who starred this news
placement (int)
The placement field is intuitive: if you order all the news by the total_stars field you get each news placement. So, the news with most stars will be number 1, and so on.
So, suppose I have 700 records in my table_news_stats, and for each one I have the id and the total_stars count, how can I update the placement field automatically for each record? Which query is faster/better?
Example of the table_news_stats content:
First record (A):
1-3654-?
Second record (B):
2-2456-?
Third record (C):
3-8654-?
If you order the record by stars count:
the sequence of records is C - A - B
So... the result will be:
First record (A):
1-3654-2
Second record (B):
2-2456-3
Third record (C):
3-8654-1
Clarification:
why would I ever need the placement field at all?
It's pretty simple... the placement field will be populated by a cronjob the first day of every month. Basically it will provide a 'snapshot' of the rank of each news in terms of popularity (as it was at the beginning of the current month). As a consequence, thanks to the placement field, I will have the following information:
"The 1st day of this month the 'top starred' news list was like this:
1- News C
2- NewsA
3- News B "
Then, with a query "SELECT * FROM table_news_stats ORDER BY total_stars DESC" I can obtain the new ranking (in real-time).
As a consequence, I will have the following information:
"At the time the page is loaded, the 'top starred' news list is like this:
1- News A
2- News C
3- News B "
Finally, by comparing the two rankings, I obtain the last piece of information:
"News A has gained a position" +1
"News C has lost a position" -1
"News B has no change in position" +0
If there is a better way of doing this, let me know.
I guess you don't need to update the table just:
SELECT *
FROM table_news_stats
ORDER BY total_stars DESC
But if you want to know the place of each one you can:
SELECT *, IF(#idx IS NULL,#idx:= 1,#idx:= #idx+1)
FROM table_news_stats
ORDER BY total_stars DESC
And if you still need to update something like:
UPDATE table_news_stats
SET placement = FIND_IN_SET(id_news,(SELECT GROUP_CONCAT(t.id_news) FROM (SELECT id_news
FROM table_news_stats
ORDER BY total_stars DESC) t ))
SQLFiddle
Consider the following
mysql> select * from test ;
+------+-------------+-----------+
| id | total_stars | placement |
+------+-------------+-----------+
| 1 | 3 | 0 |
| 2 | 6 | 0 |
| 3 | 7 | 0 |
| 4 | 2 | 0 |
| 5 | 9 | 0 |
| 6 | 2 | 0 |
| 7 | 1 | 0 |
+------+-------------+-----------+
Now using the following you can update the placement as
update test t1 join
(
select *,
#rn:= if(#prev = total_stars,#rn,#rn+1) as rank ,
#prev:= total_stars
from test,(select #rn:=0,#prev:=0)r
order by total_stars desc
)t2
on t2.id = t1.id
set t1.placement = t2.rank ;
mysql> select * from test order by placement ;
+------+-------------+-----------+
| id | total_stars | placement |
+------+-------------+-----------+
| 5 | 9 | 1 |
| 3 | 7 | 2 |
| 2 | 6 | 3 |
| 1 | 3 | 4 |
| 4 | 2 | 5 |
| 6 | 2 | 5 |
| 7 | 1 | 6 |
+------+-------------+-----------+
Note that in case of tie will have the same placement.