Group by issue in sql server [duplicate] - sql-server-2008

This question already has answers here:
Does COUNT(*) always return a result?
(7 answers)
Closed 9 years ago.
Hi all I have written a query to display the sum of quantity as follows without group by
SELECT ISNULL(SUM(VUItems.Quantity), 0) AS OrderQty
FROM VUItems
This returns as 0.00 but the same query when using group by not displaying 0.00 what might be the problem
SELECT ISNULL(SUM(VUItems.Quantity), 0) AS OrderQty
FROM VUItems
GROUP BY SKU,
SalesOrderNo
Why I need is that I will have a table which will have the quantity on saving this is what I have written to display the Quantity ordered or user eneterd as follows
SELECT VU1.*,
VU1.Quantity - (SELECT ISNULL(SUM(VU2.Quantity), 0) AS OrderQty
FROM VU2
WHERE VU1.SKU = VU2.SKU
AND VU1.SalesOrderNo = VU2.SalesOrderNo
GROUP BY SKU) AS orderedQuantity
FROM VU1
with out group by it is displaying orderedQuantity as required but with group by it is showing null

The ISNULL needs to be inside the SUM. SUM(NULL) is NULL.

Related

Get Top 5 latest records for different IDs in SQL [duplicate]

This question already has answers here:
SQL select only rows with max value on a column [duplicate]
(27 answers)
Closed 2 months ago.
I have a table named Work_Items like this:
Assume there are lots of Names (i.e., E,F,G,H,I etc.,) and their respective Date and Produced Items in this table. It's a massive table, so I'd want to write an optimised query.
In this, I want to query the latest A,B,C,D records.
I was using the following query:
SELECT * FROM Work_Items WHERE Name IN ('A','B','C','D') ORDER BY Date DESC OFFSET 0 LIMIT 4
But the problem with this query is, since I'm ordering by Date, the latest 4 records I'm getting are:
I want to get this result:
Please help me in modifying the query. Thanks.
On MySQL 8+, we can use ROW_NUMBER:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Date DESC) rn
FROM Work_Items
WHERE Name IN ('A', 'B', 'C', 'D')
)
SELECT Name, Date, ProducedItems
FROM cte
WHERE rn = 1
ORDER BY Name;
You can use inner join as follows, its working on any mysql version:
select w.name, w.`date`, w.ProducedItems
from _Work_Items w
inner join (
select name, max(date) as `date`
from _Work_Items
group by name
) as s on s.name = w.name and s.`date` = w.`date` ;

Using Order by And Group By Together Eliminates some Records [duplicate]

This question already has answers here:
MySQL Group by ID and Latest Datetime
(4 answers)
MySql : Order by and Group By combining not giving the latest record
(2 answers)
MySQL: Multiple Group By With Desc Order Issue
(1 answer)
Closed 3 years ago.
user_id date
------- ---------
1 1551867583
2 1551867580
3 1551867573
2 1551867543
2 1551867521
I have a similar table structure. What I want to do is to select records per user and select the latest one of each user's record.
Tried
GROUP BY profile_visits.user_id ORDER BY profile_visits.date DESC
This doesn't show all the latest records.
I searched and found this on StackOverflow
group by and order by in mysql query
However, that solution didn't work for me
Any idea how to solve this?
You can use max date and group by
select max(date) max_date, user_id
from my_table
group by user_id
order by user_id, max_date

Get the most often occurring year [duplicate]

This question already has answers here:
Find most frequent value in SQL column
(11 answers)
Closed 4 years ago.
I have the following table from a factory database called world in MySQL Workbench:
Table: country
Relevant Columns:
Code char(3) PK,
IndepYear smallint(6)
I'd like to get the year (or possibly years) when the most countries have become independent. I don't want to list anything else just the year(s), one row per year.
EDIT:
I have found the right solution that actually works.
SELECT IndepYear
FROM (SELECT IndepYear,
COUNT(IndepYear) AS Years
FROM world.country
GROUP BY IndepYear
ORDER BY Years DESC) AS T1
WHERE Years IN (SELECT Years
FROM (SELECT IndepYear,
COUNT(IndepYear) AS Years
FROM world.country
GROUP BY IndepYear
ORDER BY Years DESC
LIMIT 1) AS T2
GROUP BY IndepYear)
ORDER BY IndepYear ASC;
It sounds like you just want to ORDER BY the COUNT of IndepYear. Don't forget that you'll also want to GROUP BY this column, along with adding a LIMIT of 1 to get the most frequently occuring year when sorting it in descending order.
SELECT `IndepYear`,
COUNT(`IndepYear`) AS `CommonYear`
FROM `country`
GROUP BY `IndepYear`
ORDER BY `CommonYear` DESC
LIMIT 1;
Use aggregation to get the count of each year and limit it to the maximum count in a HAVING clause. Use a subquery to get the maximum count, aggregating the aggregation.
SELECT indepyear
FROM country
GROUP BY indepyear
HAVING count(*) = (SELECT max(c)
FROM (SELECT count(*) c
FROM country
GROUP BY indepyear) x);
SQL Fiddle

getting the lowest count value in mysql [duplicate]

This question already has answers here:
Mysql - Get row with lowest relation count
(2 answers)
Closed 4 years ago.
I just want the most least repeated count like in the image 1 only to be displayed. But i am having problem
SELECT bidprice, user_id, COUNT(*)
FROM auction_details WHERE product_id = '1'
GROUP BY bidprice
if you need only the lower count result you could using limit 1
SELECT bidprice, user_id, COUNT(*) my_count
FROM auction_details WHERE product_id = '1'
GROUP BY bidprice
order by my_count ASC limit 1

Select full row containing max value for each day [duplicate]

This question already has answers here:
SQL select only rows with max value on a column [duplicate]
(27 answers)
Closed 4 years ago.
My table has the following structure:
sensor_id | timestamp | value
-----------|------------|-------
1 | 1516905900 | 100.1
4 | 1516916920 | 90.4
... | ... | ...
I need to select the columns with the max value for each day for a given sensor_id. I need the timestamp associated with each max value in the results.
I have had some success using MAX() and GROUP BY and DATE_FORMAT, but I cannot get my query to include the timestamp associated with the max value for each group.
This is what I have so far:
select DATE_FORMAT(from_unixtime(timestamp), '%m/%d/%Y') as x, max(value) from sensor_log where sensor_id=6 group by x;
The result only includes the x and max(value) columns. I think it might be possible to use some sort of JOIN to get the rest of the columns, but I haven't been able to figure it out.
Another issue I can foresee is the possibility of a sensor_id having multiple occurrences of the max value on the same day, in this case I would only like to keep the first occurrence of that value for that day.
Hmmm. This sounds like a good use of a correlated subquery with a twist:
select date(from_unixtime(sl.timestamp)) as dte, sl.sensor_id, sl.value, sl.timestamp
from sensor_log sl
where sl.timestamp = (select sl2.timestamp
from sensor_log sl2
where sl2.sensor_id = sl.sensor_id and
date(from_unixtime(sl2.timestamp)) = date(from_unixtime(sl.timestamp))
order by sl2.value desc, sl.timestamp asc
limit 1
);
Starting with MySQL version 8, this can be accomplished with a ranking function dense_rank.
select sensor_id,timestamp,value,DATE_FORMAT(from_unixtime(timestamp),'%m/%d/%Y') as dt
from (select t.*
,dense_rank() over(partition by DATE_FORMAT(from_unixtime(timestamp),'%m/%d/%Y') order by value desc) as rnk
from tbl t
) t
where rnk=1