Adding a total row - mysql

I have a query;
select ProductID, name, (unitPrice*quantity) As 'Stock Equity'
from tproduct
group by productID with rollup
;
I wish for this to return a set of rows with the last being a calculation of the Total, instead its repeating the last result?
can anyone tell me why and how to overcome this please?
this is the query result at the moment;
ProductID Name Stock Equity
1 cannon 600 D 3360
2 cannon 550 D 1000
3 cannon 500 D 750
4 cannon 5D 5000
5 cannon 650 D 9000
6 Nikon D5100 1000
7 Nikon D3200 420
8 Nikon D7000 2700
9 Nikon D800 6030
10 Nikon D90 4770
null Nikon D90 4770

You can use UNION ALL:
select ProductID, name, (unitPrice*quantity) As 'Stock Equity'
from tproduct
union all
select 'total', 'total', sum(unitPrice*quantity)
from tproduct
See SQL Fiddle with Demo
Or you can use something like this:
select case when ProductID is null then 'total' else ProductId end Productid,
case when ProductID is null then 'total' else name end name,
sum(unitPrice*quantity) As 'Stock Equity'
from tproduct
group by ProductID with rollup
See SQL Fiddle with Demo

select ProductID,
name,
(unitPrice*quantity) As 'Stock Equity',
(select sum(unitPrice*quantity) from tproduct) As total
from tproduct
group by productID

Related

How to group the data properly by multiple columns?

I have a database table that represents concert hall and it looks as following:
Columns: ActionID, RegionName, RowNumber, Price, Quantity
The sample data:
ActionID RegionName RowNumber Price Quantity
1 Region1 22 8000 7
1 Region1 - 8000 1
1 Region2 10 5000 2
1 Region2 10 5000 2
1 Region2 10 5000 1
I should display particular regions with overall quantity per region grouped by ActionID, RegionName, Price and Quantity.
1 Region1 22 8000 8
1 Region2 10 5000 5
As you can see the RowNumber should be displayed, but not taken into account in grouping.
How can I do that?
You could use a CTE and ranking function like ROW_NUMBER:
WITH CTE AS
(
SELECT t.*,
rn = ROW_NUMBER()OVER(Partition By ActionID, RegionName, Price
Order By RowNumber),
OverallQuantity = SUM(Quantity) OVER (Partition By ActionID, RegionName, Price)
FROM dbo.TableName t
)
SELECT ActionID, RegionName, RowNumber, Price, Quantity = OverallQuantity
FROM CTE
WHERE RN = 1
Result:
ActionID RegionName RowNumber Price Quantity
1 Region1 - 8000 8
1 Region2 10 5000 5
Demo
You could use something like this:
SELECT ActionId,
RegionName,
MAX(RowNumber),
MAX(Price),
SUM(Quantity)
FROM #tblTest
GROUP BY ActionId, RegionName
But if there are more RowNumber or Price, it should be modified the query
You can apply a MAX or MIN to collapse the rows:
SELECT MAX(ActionID), RegionName, MAX(RowNumber), MAX(Price), SUM(Quantity)
FROM my_table
GROUP BY RegionName
This obviously gets more complicated if you have multiple ActionID or RowNumber or Price per region. In that case, only use this if you don't care which one of these multiple values you get back.

SQL display the total sales

I want to select a total sales of each Category
Here is my table: (catNo = Category No. prodNo = product No.)
OrderLine:
prodNo ordNo actualPrice qty
P0001 OR001 3.00 20
P0002 OR002 3.00 2
P0003 OR003 500.00 25
Product:
prodNo prodName prodPrice prodPhoto stockQty catNo suppNo
P0001 OverPower 1500.00 OP_C4_Black.jpg 10 CAT05 S0001
P0002 Vain 300.00 Vain.jpg 5 CAT04 S0002
P0003 test 500.00 test.jpg 40 CAT05 S0001
my SQL command is
SELECT `catNo` , sum(`actualPrice`*`qty`)as `Total Sales`
FROM `orderline` , `product`
WHERE `orderline`.`prodNo` = `product`.`prodNo`
GROUP BY `orderline`.`prodNo`;
What I want is
catNo Total Sales
CAT05 12560.00
CAT04 6.00
What actual output is
catNo Total Sales
CAT05 60.00
CAT04 6.00
CAT05 12500.00
How can I display the total sales of each Category?
SELECT `catNo` , sum(`actualPrice`*`qty`)as `Total Sales`
FROM `orderline` , `product`
WHERE `orderline`.`prodNo` = `product`.`prodNo`
GROUP BY `catNo`;
Try this, I hope it helps.
Instead of grouping by product number you should be grouping by category number:
SELECT `catNo` , sum(`actualPrice`*`qty`)as `Total Sales`
FROM `orderline` , `product`
WHERE `orderline`.`prodNo` = `product`.`prodNo`
GROUP BY `Product`.`catNo`;
Group by catNo. Then you will get the desired result:
SELECT `catNo` , sum(`actualPrice`*`qty`)as `Total Sales`
FROM `orderline` , `product`
WHERE `orderline`.`prodNo` = `product`.`prodNo`
GROUP BY `catNo`
Result:
catNo Total Sales
-------------------
CAT04 6
CAT05 12560
Sample result in SQL Fiddle

MYSQL - additional analysis on sum(field) grouped by name

I have an orders table with the following fields : id, name, price_paid
The easiest part is this:
SELECT
name,
SUM(price_paid) AS total_price_paid
FROM
Orders GROUP BY
name
How should I modify my SQL statement so I get the following at the output?
name, total_price_paid, purchase_level
Where purchase level would be:
1 if total_price_paid is in the range of 0 - 100
2 if in a range 101-350
and 3 if above 350
Thank you in advance.
SELECT
name,
SUM(price_paid) AS total_price_paid,
CASE WHEN SUM(price_paid) BETWEEN 0 AND 100 THEN 1
WHEN SUM(price_paid) BETWEEN 101 AND 350 THEN 2
WHEN SUM(price_paid) > 350 THEN 3 END AS purchase_level
FROM
Orders
GROUP BY
name
Use conditional sum:
SELECT
name,
SUM(IF(price_paid BETWEEN 0 AND 100, price_paid, 0)) AS sum_0_100,
SUM(IF(price_paid BETWEEN 101 AND 350, price_paid, 0)) AS sum_101_350,
SUM(IF(price_paid>350, price_paid, 0)) AS sum_350_plus
FROM
Orders
GROUP BY
name
Or else, with level:
SELECT
name,
SUM(price_paid),
CASE
WHEN price_paid BETWEEN 0 AND 100 THEN 1
WHEN price_paid BETWEEN 101 AND 350 THEN 2
WHEN price_paid>350 THEN 3
END AS level
FROM
Orders
GROUP BY
name,
-- don't forget group then:
level
Difference between those two queries are that fires will result in pivot while second will result in plain rows grouping.

How to (MySQL) multiply columns and then the sum rows?

I've got this table:
id | payment_id | quantity | unit cost
1 633 1 750
2 633 1 750
3 632 2 750
4 632 2 750
What I need is :
payemnt_id | total
633 1500
632 3000
You can also think of this as Countries and then you are trying to find the total for each Country. I was sure there were some tutorials like this but could not find by STFW.
You can simply put the formula (expression) inside SUM:
SELECT payment_id, SUM(`unit cost` * quantity) AS total
FROM myTable
GROUP BY payment_id
SELECT
payment_id,
SUM(subtotal) AS total
FROM(
SELECT
payment_id,
(unit_cost * quantity) AS subtotal
) AS t1
GROUP BY
payment_id
SELECT payemnt_id, SUM(`unit cost` * quantity) as total
FROM Table1
GROUP BY payemnt_id
SELECT COALESCE (SUM(cost_field * quantity_field),0) AS tot FROM Table_Name
I Think This One Is Good, Why ?
Because If Their is No Result It Will Give You Zero

TSQL to return the dates of price changes from a price history

I have a price history table that has these 4 fields
Id
Date
Product
Price
There is a record for ever day for every product. I'm trying to write a query to return a record for the starting price of each product along with a record for each time the price changed.
I tried grouping by price but obviously this breaks when a price changes than at a later date changes back as it will only return 1 record.
I've written this query to generate sample data that I am trying to work off
CREATE TABLE #PriceHistory
(
[Id] INT IDENTITY,
[Date] DATETIME ,
[Product] NVARCHAR(30) ,
[Price] MONEY
)
INSERT INTO #PriceHistory([Date],[Product],[Price])
SELECT '20120101', 'Tesco', 1.99
UNION ALL
SELECT '20120102', 'Tesco', 1.97
UNION ALL
SELECT '20120103', 'Tesco', 1.97
UNION ALL
SELECT '20120105', 'Tesco', 1.99
UNION ALL
SELECT '20120104', 'Tesco', 1.99
UNION ALL
SELECT '20120106', 'Tesco', 1.99
UNION ALL
SELECT '20120101', 'BP', 1.99
UNION ALL
SELECT '20120102', 'BP', 1.01
UNION ALL
SELECT '20120103', 'BP', 1.99
SELECT * FROM #PriceHistory
DROP TABLE #PriceHistory
From that sample data the results I'm expecting should be
1 2012-01-01 Tesco 1.99
2 2012-01-02 Tesco 1.97
5 2012-01-04 Tesco 1.99
9 2012-02-11 BP 1.99
8 2012-02-20 BP 1.01
Any ideas on the best way to achieve this?
This query starts with a price, and attempts to find the previous record for the same product with the same price... if there's no record for the same product at the same price, it returns the record:
SELECT ph.*
FROM
#PriceHistory ph
LEFT JOIN #PriceHistory ph2 ON
ph.Product = ph2.Product
AND ph.Price = ph2.Price
AND ph2.Date = (
SELECT MAX(ph3.Date)
FROM #PriceHistory ph3
WHERE
ph3.Product = ph.Product
AND ph3.Date < ph.Date
)
WHERE ph2.ID IS NULL
Not very well tested, but try this:
SELECT DISTINCT P1.* FROM #PriceHistory P1
JOIN #PriceHistory P2 ON P1.Date = P2.Date + 1
OR P1.Date in (SELECT MIN(Date) From #PriceHistory P3)
WHERE P1.Product = P2.Product AND P1.Price <> P2.Price
Adjacent dates; same products; different price
[EDIT to capture the "first" date]