select avg(),min(),max(),toatl(),count() of selected result - sql-server-2008

I am trying to calculate average,min,max,total,count but i am getting wrong result.
SELECT t0.brandID, t0.brandName, t0.cdt, t0.udt, t0.brandstatus, t0.AddedBy ,
AVG(t0.brandID) AS brandID_AVERAGE,
min(t0.brandid) as branid_min,
MAX(t0.brandid) as brandid_max,
COUNT(t0.brandid) as brandid_count
FROM brands t0
Where t0. brandID=null OR t0. brandName='khasim'
group by t0.brandID,t0.brandName,t0.cdt,t0.udt,t0.brandstatus,t0.AddedBy
select AVG(CAST (brandID AS bigint)) AS brandID_AVERAGE,
min(CAST (brandID AS bigint)) as branid_min,
MAX(CAST (brandID AS bigint)) as brandid_max,
COUNT(CAST (brandID AS bigint)) as brandid_count from
(SELECT t0.brandID, t0.brandName, t0.cdt, t0.udt, t0.brandstatus, t0.AddedBy
FROM brands t0
Where t0. brandID=null OR t0. brandName='budwieser'
group by t0.brandID,t0.brandName,t0.cdt,t0.udt,t0.brandstatus,t0.AddedBy) temptable
i have changed my query to select avg etc for the result of select now
i am getting what i expect, but i want to show all selected columns in
one table how to do.
expected result
result for the above query is

Firstly. From my best knowledge in SQL null is not equal to null. So you need to use is null to check is value equals to null.
Secondly. Could you explain please what is wrong with underlined values?

Your first query where you're returning one row looks correct. Your second screenshot where you get many rows looks like you are using WINDOWING functions (i.e. anything with an OVER clause). This does not aggregate data, it returns all rows and repeats the calculations over the set while returning every row.
Can you include the full query text that is producing the incorrect result?
Also, it could be caused by brandId being an integer type, in which case all calculations on it will use integer-based arithmetic (i.e. no fractions). This is fine if you only expect integer results, but if you need fractions, try using CAST to convert all the occurrences of brandid to decimal types, like this: CAST(brandId as decimal(18, 8)) before doing the AVG and other calculations.

Related

SQL Select Max of Columns Where Date is Not Null

I currently am using this query to select some data:
SELECT DISTINCT a.code AS code, name, max(scen.Is3D) AS Is3D FROM locations LEFT JOIN .... The scen table has columns Is3D and Date. I only want to select the max of items where the date IS NOT NULL. I tried max(scen.Is3D WHERE scen.Date IS NOT NULL), but that didn't work. I cannot change anything after the FROM in my query, so I need that filtering to be done in the MAX, if possible. I am using MySQL 5.7.
You can use:
MAX(CASE WHEN scen.date IS NOT NULL THEN scen.Is3D END) AS Is3D
The CASE expression returns NULL when none of the WHEN conditions is met, but MAX() ignores null values, so this will just return the max of the Is3D columns in the selected rows.
So if we can't change anything after the FROM, then we cannot get a perfect solution here. Since you are SELECTing out the NULL values. One thing that we can try if we can only modify the final output is this.
SELECT MAX(ISNULL(scen.Date,0))...
This will replace all the NULLs with 0, but it would help to know exactly what you are trying to do. Why are you so convinced that the query itself cannot be modified in any way?
The other solution would be to put the whole query in another wrapper.
That would look like:
SELECT *
FROM (
[your whole query here]
) AS inner
WHERE inner.Date IS NOT NULL

mysql calculate percentage for diffrent groups

I want to calculate percentage for test groups.
I have group A,B and C. And I want to know how much success percentage each group have.
My first query is counting total test ran in each group by doing the following:
SELECT type, count(type) as total_runs
From mytable
Where ran_at > '2015-09-11'
Group by type
Second query is counting success for each group:
SELECT type, count(type) as success
FROM mytable
where run_status like '%success%' and ran_at> '2015-09-11'
Group by type
Now I need to divide one in the other and multiply in 100.
how do I do this in one query in an efficient way, I guess nested query is not so efficient- but anyway I can't see how I can uses nested query to solve it.
I would appreciate answer which include simple way, maybe not so efficient, and an efficient way with explanations
You can just use conditional aggregation:
SELECT type, sum(run_status like '%success%') as success,
100 * avg(run_status like '%success%') as p_success
FROM mytable
where ran_at> '2015-09-11'
Group by type;
In a numeric context, MySQL treats boolean expressions as integers with 1 for true and 0 for false. The above works assuming that run_status is not NULL. If it can be NULL, then you need an explicit case statement for the avg().
I had this one, but Gordon have a better solution if run_status is not NULL.
Select type, sum(if(run_status like '%success%',1,0)) / count(1) * 100) as p_success
From mytable
Where ran_at > '2015-09-11'
Group by type

Trouble in SQL Summing a Word

I am trying to Sum() the column Status where Status = 'operational'. I am having trouble figuring out how to sum the actual word "operational".
I have tried multiple different variations of the statement below (the one I posted is the most basic form) but I get the error: data type varchar is invalid for sum operator.
Can anybody help?
SELECT SUM(status) As 'TotalOperationalSTIDevices'
FROM netinfo_device_details
WHERE LoopBackAddress LIKE '10.12%' AND Status = 'Operational'
Try
Select COUNT(*) As 'TotalOperationalSTIDevices' from netinfo_device_details where LoopBackAddress Like '10.12%' and Status = 'Operational'
You need to use COUNT:
SELECT COUNT(*) As TotalOperationalSTIDevices
FROM netinfo_device_details
WHERE LoopBackAddress LIKE '10.12%' AND Status = 'Operational';
The SUM aggregation function really does a SUM of a set of numbers. COUNT just counts the number of rows.
Since the actual content of the row is not relevant, you can use COUNT(*) instead of COUNT(status) if you want.

how to select and set value as 0 even if there is no value or data stored in database

Is there any select query that set value as 0 even if it is empty or no record stored in database?
Because I am trying to subtract values from two different tables. But the problem is that I cant subtract the the tables if one of them is no data stored.
Here is my code. This code can subtract if both tables have value.
SELECT category,(SELECT SUM(s.total)-SUM(r.total)
FROM rsales AS s WHERE r.pcode=s.pcode
) as total,
r.pcode
FROM rreturn AS r
GROUP BY r.pcode;
Use IFNULL or COALESCE:
SELECT IFNULL(SUM(s.total), 0)
SELECT COALESCE(SUM(s.total), 0)
If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2.
IFNULL() returns a numeric or string value, depending on the context in which it is used.
something like this should work
SUM(IF(s.total, s.total, 0))
OR
SUM(IFNULL(s.total), 0))
The syntax you're using is both confusing and error prone. I would go for something simpler like this:
SELECT category, SUM(s.total) - SUM(r.total) total
FROM rsales s
LEFT JOIN rreturn r USING (pcode)
GROUP BY s.pcode;
This assumes rreturn may not have records for each pcode.

How to get the max value of a field without grouping in MySql

I have a query with many wheres and orders criterias. One of the fields of the select is 'price' (element price) but I would like to have also (in every row) the maximun price of all the selected elements.
I tried to include MAX aggregate function on select hoping that this will return desired value, but insetead of that, price and MAX(price) returns the same. Searching into MySql doc I found the reason:
If you use a group function in a
statement containing no GROUP BY
clause, it is equivalent to grouping
on all rows.
Is there a way to solve this problem?
Thanks in advance!
There's a similar question (but not resolving this): find max value without aggregate operator in mysql
You can do this:
SELECT
id,
price,
(SELECT MAX(price) FROM your_table) AS max_price
FROM your_table
I'm not sure why you'd want to return that value on every row though... I'd probably do this in two separate queries, or else use a UNION ALL:
SELECT id, price FROM your_table
UNION ALL
SELECT NULL, MAX(price) FROM your_table
Maybe you could use a stored procedure like so:
CREATE PROCEDURE QueryWithMax ([parameter list if necessary])
BEGIN
-- Obtain the maximum price
DECLARE x INT UNSIGNED; -- change datatype if appropriate
SET x = SELECT
MAX(price)
FROM
...
WHERE
...
;
-- Now do your query
SELECT
price,
[other columns],
x AS MaxPrice
FROM
...
WHERE
...
GROUP BY
...
;
END
I haven't tried this, but if you had a subquery that extracts the maximum price (so you get one row), and then do a cross join (cartesian product) with it. You should get something like what you want. I can't vouch for how fast this would be.