mysql Group by in nested query - mysql

I have employee_id,status and payment field. I need to produce two different output ( sum(payment)) with two different condition.
The problem is when i use group by, it produce the total sum of all rows, whilst I want it to group by the employee id.
this is my query:
select employee_id,
(select sum(payment) from tblempay where status=1) AS 'Total 1',
(select sum(payment) from tblempay where status=2) AS 'Total 2'
from tblempay
group by employee_id
hope somebody can help me. Thank you.

Try this;)
select employee_id,
sum(if(status=1, payment, 0)) AS `Total 1`,
sum(if(status=2, payment, 0)) AS `Total 2`
from tblempay
group by employee_id

Related

Add additional column to the query output

I have the following query that is grabbing data from a table and combining all the products into one column and counting the quantity of that order.
I need to add an additional column to the output though, how can I also add ship_date?
select order_id, group_concat(product_id, ' - ', cnt separator ', ') as products, sum(cnt) as total
from (select order_id, product_id, count(*) as cnt
from tt_order_items
group by order_id, product_id
) op
group by order_id;
This is how the original table is laid out:
And this is how the query outputs the results:
How can I add ship_date to that output?
It looks like ship_date is fixed for each and every order_id. If so, you can just add it to the inner and outer aggregation:
select
order_id,
group_concat(product_id, ' - ', cnt separator ', ') as products,
sum(cnt) as total,
ship_date
from (
select order_id, product_id, count(*) as cnt, ship_date
from tt_order_items
group by order_id, product_id, ship_date
) op
group by order_id, ship_date;

MySQL Add Total at bottom of search result if there is one or more records has been found

I have below SQL statement to generate a total at bottom of search result but I do not want to display Total if there is no record has been found. Need help on below Statement.
SELECT Member_ID, Order_Total, Shipping_Cost, TAX FROM Order Where
Order_Total > 100
UNION (
SELECT "Total" as Member_ID, sum(Order_Total) as Order_Total, sum(Shipping_Cost) as Shipping_Cost, sum(TAX) as TAX FROM Order Where
Order_Total > 100);
You don't need UNION, you can use the WITH ROLLUP option to make an automatic total. If the query doesn't select any rows, the result will be empty.
SELECT IFNULL(Member_ID, 'Total') AS Member_ID, Order_Total, Shipping_Cost, TAX
FROM (
SELECT Member_ID, sum(Order_Total) as Order_Total, sum(Shipping_Cost) as Shipping_Cost, sum(TAX) as TAX
FROM `Order`
Where Order_Total > 100
GROUP BY Order_ID
WITH ROLLUP) AS x
Another way is to keep your UNION, but add a HAVING clause to the second query.
SELECT Member_ID, Order_Total, Shipping_Cost, TAX
FROM `Order`
Where Order_Total > 100
UNION (
SELECT "Total" as Member_ID, sum(Order_Total) as Order_Total, sum(Shipping_Cost) as Shipping_Cost, sum(TAX) as TAX
FROM `Order`
Where Order_Total > 100
HAVING COUNT(*) > 0);

Coalesce with Roll Up not working correctly (MySql)

I am trying to coalesce on the roll up (against the year revenue), The roll up is calculating correctly, however instead of inputting 'Grand Total' at the end of the table, 'Socks' is being inputted again.
Any ideas what i am doing wrong?
select coalesce(product_name, 'total') as product_name, sum(price) as year_revenue
from orders
join product on orders.ProductID = product.ProductID
group by month(order_data) with rollup;
'Blue Shirt', '69.93'
'Denim Jeans', '197.91'
'White Blazer', '94.97'
'Socks', '109.94'
'Skinny Jeans', '73.96'
'Mini Skirt', '31.98'
'White Blazer', '74.97'
'Black Blazer', '40.99'
'Shorts', '19.98'
'Mini Skirt', '85.96'
'Flare Blouse', '33.98'
'Socks', '7.98'
'Socks', '842.55'
The reason for this is that you are grouping by MONTH(order_data), not product_name. When WITH ROLLUP happens, it is the grouped by column value that gets replaced by NULL. If you were to change your query to:
SELECT MONTH(order_data) AS month, product_name, SUM(price) AS year_revenue
FROM orders
JOIN product ON orders.ProductID = product.ProductID
GROUP BY month WITH ROLLUP
You would see the NULL values in the month column.
To achieve what you want, try changing your query to this:
SELECT IF(month IS NULL, 'Total', product_name) AS product_name, year_revenue
FROM (SELECT MONTH(order_data) as month, product_name, SUM(price) AS year_revenue
FROM orders
JOIN product ON orders.ProductID = product.ProductID
GROUP BY month WITH ROLLUP)

making a query for stock/price trend in mysql

SQL Fiddle
Table scheme:
CREATE TABLE company
(`company_id` int,`name` varchar(30))
;
INSERT INTO company
(`company_id`,`name`)
VALUES
(1,"Company A"),
(2,"Company B")
;
CREATE TABLE price
(`company_id` int,`price` int,`time` timestamp)
;
INSERT INTO price
(`company_id`,`price`,`time`)
VALUES
(1,50,'2015-02-21 02:34:40'),
(2,60,'2015-02-21 02:35:40'),
(1,70,'2015-02-21 05:34:40'),
(2,120,'2015-02-21 05:35:40'),
(1,150,'2015-02-22 02:34:40'),
(2,130,'2015-02-22 02:35:40'),
(1,170,'2015-02-22 05:34:40'),
(2,190,'2015-02-22 05:35:40')
I'm using Cron Jobs to fetch company prices. In concatenating the price history for each company, how can I make sure that only the last one in each day is included? In this case, I want all of the price records around 05:30am concatenated.
This is the result I'm trying to get (I have used Date(time) to only get the dates from the timestamps):
COMPANY_ID PRICE TIME
1 70|170 2015-02-21|2015-02-22
2 120|190 2015-02-21|2015-02-22
I have tried the following query but it doesn't work. The prices don't correspond to the dates and I don't know how to exclude all of the 2:30 am records before applying the Group_concat function.
SELECT company_id,price,trend_date FROM
(
SELECT company_id, GROUP_CONCAT(price SEPARATOR'|') AS price,
GROUP_CONCAT(trend_date SEPARATOR'|') AS trend_date
FROM
(
SELECT company_id,price,
DATE(time) AS trend_date
FROM price
ORDER BY time ASC
)x1
GROUP BY company_id
)t1
Can anyone show me how to get the desired result?
Ok, so this should work as intended:
SELECT p.company_id,
GROUP_CONCAT(price SEPARATOR '|') as price,
GROUP_CONCAT(PriceDate SEPARATOR '|') as trend_date
FROM price as p
INNER JOIN (SELECT company_id,
DATE(`time`) as PriceDate,
MAX(`time`) as MaxTime
FROM price
GROUP BY company_id,
DATE(`time`)) as t
ON p.company_id = t.company_id
AND p.`time` = t.MaxTime
GROUP BY p.company_id
Here is the modified sqlfiddle.
This is a bit unorthodox but I think it solves your problem:
SELECT company_id,
GROUP_CONCAT(price SEPARATOR'|'),
GROUP_CONCAT(trend_date SEPARATOR'|')
FROM (
SELECT *
FROM (
SELECT company_id,
DATE(`time`) `trend_date`,
price
FROM price
ORDER BY `time` DESC
) AS a
GROUP BY company_id, `trend_date`
) AS b
GROUP BY company_id

SQL Sum cumulative and non-cumulative in same query

Hi I was wondering if there is a way to get a cumulative and non-cumulative total in the same query. I have a table with following fields:
Department, SalesPerson, fin_month, activity, cost
What I would like is have two sums, one that would give a monthly total for salesperson, and another giving a year to date total. I am having a problem setting two different where criteria to get it to work.
Many Thanks
Would something like this help?
SELECT
*
FROM
(
SELECT
Department, SalesPerson
, SUM(fin_month) SalesPerson_Sum
FROM
[TABLE_NAME]
GROUP BY Department, SalesPerson
) a
INNER JOIN
(
SELECT
Department
, SUM(fin_month) AS Department_Sum
FROM
[TABLE_NAME]
GROuP BY
Department
) b
ON
a.Department = b.Department
This solution uses CTEs, recursion, and ranking to obtain cumulative totals for every fin_month per SalesPerson in every Department based on the corresponding monthly totals.
;WITH
monthlytotals AS (
SELECT
Department,
SalesPerson,
fin_month,
MonthlyTotal = SUM(cost),
rn = ROW_NUMBER() OVER (PARTITION BY Department, SalesPerson
ORDER BY fin_month)
FROM atable
GROUP BY Department, SalesPerson, fin_month
),
alltotals AS (
SELECT
Department,
SalesPerson,
fin_month,
MonthlyTotal,
CumulativeTotal = MonthlyTotal,
rn
FROM monthlytotals
WHERE rn = 1
UNION ALL
SELECT
m.Department,
m.SalesPerson,
m.fin_month,
m.MonthlyTotal,
CumulativeTotal = a.CumulativeTotals + m.MonthlyTotal,
m.rn
FROM monthlytotals m
INNER JOIN alltotals a
ON m.Department = a.Department
AND m.SalesPerson = a.SalesPerson
AND m.rn = a.rn + 1
)
SELECT
Department,
SalesPerson,
fin_month,
MonthlyTotal,
CumulativeTotal
FROM alltotals