• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

SQL help with count after group by

rh71

No Lifer
Have a Device table and a Batterylife table which captures the battery percentage of devices at the same time every day. I'm trying to display the average battery life per device as well as (and here's the issue) give a count of how many devices were captured within the time frame I'm trying to display.

Device Table:
DeviceIDDeviceModel
1iphone 10
2iphone 13
3galaxy S22
4galaxy S9

Batterylife Table:
DeviceIDRecordedDateTimeBatteryPercent
16/9/22 12:00:0088
26/9/22 12:00:0094
36/9/22 12:00:0096
46/9/22 12:00:0093
16/7/22 12:00:0066
26/7/22 12:00:0072
16/5/22 12:00:0055
26/5/22 12:00:0043
36/5/22 12:00:0066
46/5/22 12:00:0067

Current query:
SQL:
SELECT d.DeviceModel, avg(b.BatteryPercent) as Percent
FROM Device d INNER JOIN Batterylife b on d.DeviceID = b.DeviceID
WHERE b.RecordedDateTime > '6/7/22 0:00:00'
GROUP BY d.DeviceModel

Which produces:
DeviceModelPercent
iphone 1077
iphone 1383
galaxy S2296
galaxy S993

Now I want to add a "count of devices" column (as theCount) that was included in the time constraint of the query (of 6/7/22 onward), which should look like this since only the iphones were recorded 2 times since 6/7/22:
DeviceModeltheCountPercent
iphone 10277
iphone 13283
galaxy S22196
galaxy S9193

I can't figure out how to adjust the above query since if I just add a select count(d.DeviceModel) in there, it actually counts all the rows regardless of the time period I queried. I'm thinking I need a subquery of some sort but what I've tried results in counting ALL the rows just the same.
 
Last edited:
I don't see any reason why count doesn't work here. Just try a simple `
SELECT DeviceModel, COUNT(DeviceModel) AS theCount FROM Device GROUP BY DeviceModel`, you should get count per model. Should be no different if you add the COUNT to your existing SQL
 
You can, in fact, just add `Count(1)` or `count(*)` and that will work with the group by statement to count each row present in the group.
 
Back
Top