Finding The Sum OF Two Values In SQL Server 2008 - sql-server-2008

I have a table Usage and it contains the following columns
sl_No
usage_ID
energyItem_ID
qty
unit_ID
location_ID
p_Rate
Sometimes the same EnergyItem might be located at different locations..
During those conditions how can I get the sum of qty of an individual energyItem..
How to get the sum of the qty of energyItems?

If I've understood correctly, you're trying to find the quantity of each
energy item, regardless of its location, using information in a single table.
The following query will give you the energyItem_ID of each item followed by the total quantity of each item:
SELECT energyItem_ID,Sum(qty) as TotalQuantity
FROM Usage
GROUP BY energyItem_ID
ORDER BY energyItem_ID
If, on the other hand, you wanted the quantity of each energy item, broken down by location, you would need the following:
SELECT location_ID,energyItemID,Sum(qty) as QuantityByLocation
FROM Usage
GROUP BY location_ID,energyItemID
ORDER BY location_ID,energyItemID
The order by clauses make the result easier to follow, but are not strictly necessary.
Finally, the answer by marc_s will give you the quantity of a specific energyItem.

How about:
SELECT EnergyItem_ID, SUM(qty)
FROM dbo.Usage
WHERE EnergyItem_ID = 42 -- or whatever ....
GROUP BY EnergyItem_ID
Or what are you looking for?? The question isn't very clear on the expected output....

select a.usage_ID , b.sum(p_Rate) as total from Table_1 a
inner join Table_2 as b on a.usage_ID = b.usage_ID
group by a.usage_ID

Related

Total amount of sales done for each product using SQL

Here is the structure of 1st Table called Product.
PRODID PDESC PRICE CATEGORY DISCOUNT
101 BALL 10 SPORTS 5
102 SHIRT 20 APPAREL 10
Here is the structure of 2nd table called SaleDetail.
SALEID PRODID QUANTITY
1001 101 5
1001 101 2
1002 102 10
1002 102 5
I am trying to get total sales amount for each product by joining 2 tables. Here is the SQL i tried but its not giving correct result.
select a.prodid,
(sum((price - discount))),
sum(quantity),
(sum((price - discount))) * sum(quantity)
from product a
join saledetail b on a.prodid = b.prodid
group by a.prodid
2nd column of the query is giving incorrect final price. Please help me correct this SQL.
Please find an indicative answer to your question in the fiddle.
A problem stems from the aggregation of the difference of price. In case that the same product has two different prices, then these prices would be aggregated to one.
Moreover, you multiple the sums of the prices and quantities, while you need to perform the calculation on every sample. Look at the answer by #DanteTheSmith.
You might consider to use the SaleDetail table on the left side of your query.
SELECT SD.PRODID,
P.Price-P.Discount AS Final_Price,
SUM(SD.QUANTITY) AS Amount_Sold,
SUM((P.Price-P.Discount)*SD.QUANTITY) AS Sales_Amount
FROM SaleDetail AS SD
JOIN Product AS P
ON SD.PRODID = P.PRODID
GROUP BY SD.PRODID, P.Price-P.Discount
It would help if you built the example in SQL fiddle or gave the creates for the tables, but if I have to guess your problem is:
(sum((price - discount))) * sum(quantity)
needs to be:
sum((price - discount) * quantity)
(price - discount) * quantity is the function you wanna apply PER ROW of the joined table then you wanna add all those up with SUM() when grouping by prodid.
Furthermore, you can notice that (price - discount) needs to be done ONLY ONCE PER ROW so a quicker version would be to do:
(price-discount) * sum(quantity)
That would give you the total money earned for that product across all the sales you made, and I am guessing this is what you want?
I just notice you have a problem with 2nd column, dunno if that has been in question all along:
(sum((price - discount)))
Why are you summing? Do you want the money earned per product per unit of the product? Well guess what, your price is the same all the time, same as your discount so you can simply go with:
(price-discount) as PPP
NOTE: This assumes the discount is numerical (not percentage) and is applicable to all your sales, also the price is forever the same all which is not real life like.

select returns wrong id when using max

Assuming a table like this.
id town_id begin_date
12 2 2011-10-10
23 2 2011-11-10
43 2 2012-01-01
now if I do
SELECT id, MAX(begin_date) AS mx
FROM regions
The above query returns the max date but the id is wrong:
id mx
12 2012-01-01
Is this expected?
How can I get it to return the correct id (43, 2012-01-01)
If what you are trying to do is get the id associated with the MAX() date, then you can do:
SELECT id, begin_date from regions order by begin_date DESC LIMIT 1;
You forgot the GROUP BY clause:
SELECT id, MAX(begin_date) AS mx
FROM regions
GROUP BY 1
I also want to add another possible solution to this answer which might be more intuitive because the accepted answer actually is wrong and only the comment below solves it partly. Why? Because it only works if you want a grouped result by town_id. If you you need a solution which retrieves the row with the absolute maximum date you can only go with Francisco Sotos answer or the query below.
SELECT ID, begin_date from regions WHERE begin_date = (SELECT MAX(begin_date) FROM regions)
The query I posted does not use limit but instead requires a sub query. IDK which one is faster but just as an additional food for thought.

Help with MySQL query... Need help ordering a group of rows

I can tell it best by explaining the query I have, and what I need.
I need to be able to get a group of items from the database, grouped by category, manufacturer, and year made. The groupings need to be sorted based on total amount of items within the group. This part is done with the query below.
Secondly, I need to be able to show an image of the most expensive item out of the group, which is why I use MAX(items.current_price). I thought MAX() gets the ENTIRE row corresponding to the largest column value. I was wrong, as MAX only gets the numeric value of the largest price. So the query doesnt work well for that.
SELECT
items.id,
items.year,
items.manufacturer,
COUNT(items.id) AS total,
MAX(items.current_price) AS price,
items.gallery_url,
FROM
ebay AS items
WHERE
items.primary_category_id = 213
AND
items.year <> ''
AND
items.manufacturer <> ''
AND
items.bad_item <> 1
GROUP BY
items.primary_category_id,
items.manufacturer,
items.year
ORDER BY
total DESC,
price ASC
LIMIT
10
if that doesnt explain it well, the results should be something like this
id 10548
year 1989
manufacturer bowman
total 451
price 8500.00 (The price of the most expensive item in the table/ not the price of item 10548)
gallery_url http://ebay.xxxxx (The image of item 10548)
A little help please. Thanks
I've had this same problem, and I'm fairly certain you have to do two queries (or a subquery, that's a matter of taste).
The first query is like what you have (except id isn't helping you).
The second query uses the GROUP BY fields and one (one!) MAX field to get the id and any other meta-data you need.
I believe this is the implementation, although it's hard to test:
SELECT
items.id,
items.year,
items.manufacturer,
items.gallery_url
FROM
ebay as items
NATURAL JOIN
(
SELECT
COUNT(items.id) AS total,
MAX(items.current_price) AS current_price,
items.primary_category_id,
items.manufacturer,
items.year
FROM
ebay AS items
WHERE
items.primary_category_id = 213
AND
items.year <> ''
AND
items.manufacturer <> ''
AND
items.bad_item <> 1
GROUP BY
items.primary_category_id,
items.manufacturer,
items.year
ORDER BY
total DESC,
price ASC
LIMIT
10
) as bigones
ORDER BY
bigones.total DESC,
bigones.current_price ASC
This documentation may help you understand what's going on:
http://dev.mysql.com/doc/refman/5.1/en/group-by-hidden-columns.html
... all rows in each group should have the same values for the columns that are ommitted from the GROUP BY part. The server is free to return any value from the group, so the results are indeterminate unless all values are the same.

mysql first record retrieval

While very easy to do in Perl or PHP, I cannot figure how to use mysql only to extract the first unique occurence of a record.
For example, given the following table:
Name Date Time Sale
John 2010-09-12 10:22:22 500
Bill 2010-08-12 09:22:37 2000
John 2010-09-13 10:22:22 500
Sue 2010-09-01 09:07:21 1000
Bill 2010-07-25 11:23:23 2000
Sue 2010-06-24 13:23:45 1000
I would like to extract the first record for each individual in asc time order.
After sorting the table is ascending time order, I need to extract the first unique record by name.
So the output would be :
Name Date Time Sale
John 2010-09-12 10:22:22 500
Bill 2010-07-25 11:23:23 2000
Sue 2010-06-24 13:23:45 1000
Is this doable in an easy fashion with mySQL?
I think that something along the lines of
select name, date, time, sale from mytable order by date, time group by name;
will get you what you're looking for
you need to perform a groupwise max or groupwise min
see below or http://pastie.org/973117 for an example
select
u.user_id,
u.username,
latest.comment_id
from
users u
left outer join
(
select
max(comment_id) as comment_id,
user_id
from
user_comment
group by
user_id
) latest on u.user_id = latest.user_id;
In databases, there really is no "first" or "last" record; think of each record as its own, non-positional entity in the table. The only positions they have are when you give them one, say, using ORDER BY.
This will give you what you want. It might not be efficient, but it works.
select Name, Date, Time, Sale from
(select Name, Date, Time, Sale from MyTable
order by Date asc, Time asc) MyTable_subquery_name
group by Name
Note: MyTable_subquery_name is just a dummy name for the subquery. MySQL will give the error ERROR 1248 (42000): Every derived table must have its own alias without it.
If only GROUP BY and ORDER BY were communicative operations, then this wouldn't have to be a subquery.

Join results of two select statements

I have a table serving as a transaction log:
Date Action Qty
11-23 ADD 1
11-23 REMOVE 2
11-23 ADD 3
I would like a query to aggregate all of ADDs and all of the REMOVEs separately for a given date.
Each of these select statements work fine, but they cannot be joined:
select date, sum(qty) as Added from table where action='Add' and date='11-23'
natural join
select date, sum(qty) as Removed from table where action='Remove' and date='11-23'
Can I store the results of each select statement to a table and then join those? Is there a way to avoid this all together?
Thanks-
Jonathan
Take a look at UNION syntax, if you really want to add the result sets of multiple queries into one:
http://dev.mysql.com/doc/refman/5.0/en/union.html
However, in this case, take a look at GROUP BY
You could group on Date, Action therefore resulting in one record per day per action, with SUM() being able to give you the quantity.
For example:
select
date,
action,
sum(qty) AS Quantity
from
table
group by
date, action
Will result in:
11-23 | ADD | 10
11-23 | REMOVE | 5
11-24 | ADD | 4
11-24 | REMOVE | 3
It would help if you showed what output you actually want.
From your "as Added" and "as Removed" I'm guessing that you don't want a union, but maybe something like this:
select
date,
sum(if(action='ADD',qty,0)) as Added,
sum(if(action='REMOVE',qty,0)) as Removed
from `table`
where date='11-23';
(with a group by date if you are selecting multiple dates.)