I am very new to SQL so please bear with me! I am trying to write a T-SQL query (SSMS) to retrieve two different maximum "Quantity" values from the same "Name" from a database, call it "meter_data", in the format below:
Name Date Time Value Quantity
------------------------------------------
Meter1 29-08-17 19:00 2.1 Amps
Meter1 29-08-17 19:30 2.5 Amps
Meter1 29-08-17 20:00 2.2 Amps
Meter1 29-08-17 19:00 231 Volts
Meter1 29-08-17 19:30 232 Volts
Meter1 29-08-17 20:00 235 Volts
Meter2 29-08-17 19:00 16.1 Amps
Meter2 29-08-17 19:30 17 Amps
Meter2 29-08-17 20:00 17.1 Amps
Meter2 29-08-17 19:00 415 Volts
Meter2 29-08-17 19:30 413 Volts
Meter2 29-08-17 20:00 412 Volts
etc... etc... etc... etc...
The result of the query should return the following data:
Meter 1
Amps 2.5
Volts 235
Here is my query:
SELECT MAX(Value)
FROM meter_data
WHERE Name = 'Meter1'
AND (Quantity = 'Amps')
AND (Quantity = 'Volts')
The result of the above is:
Meter1
NULL
The query is obviously incorrect, as it ANDs the two Quantity together and returns a NULL value. I have tried several different ways to achieve this (INNER JOIN, IN, INTERSECT...) but for the life of me I cannot figure out where I'm going wrong. Should there be another WHERE clause?
Not asking for a free bit of code but if someone can point me in the right direction I'll be really grateful!
Thanks.
group by:SELECT Name, Quantity, MAX(Value) FROM meter_data GROUP BY Name, Quantity