MAX query problems - sql

I'm working on an assignment and I have a table with several columns. The two I'm interested in are the Type and the Easting column.
I'm trying to use a query to return the max value from the Easting column and also show me what that value holds in the Type column.
I'm using Microsoft Access for the assignment.
Here is what I have so far, but it returns all the values not the max
SELECT Type, Location,MAX(Easting)
FROM CrimeData
GROUP BY Easting, Location, Type
Any help would be great.

You'll need to obtain the maximum Easting value (using a subquery), and then select all records which hold such value, e.g.:
select c.type, c.location, c.easting
from crimedata c
where c.easting = (select max(t.easting) from crimedata t)
Solutions which use a group by clause will only provide the maximum Easting value for records within each combination of values held by the fields in the group by clause.

You must group by all output columns except the one with the aggregate (MAX).
SELECT Type, Location, MAX(Easting)
FROM CrimeData
GROUP BY Type, Location
When you are grouping, you can filter the raw data before grouping with a WHERE clause and the grouped data after grouping with a having clause. e.g.
SELECT Type, Location, MAX(Easting)
FROM CrimeData
WHERE Type > 1
GROUP BY Type, Location
HAVING MAX(Easting) < 10

Try this:
SELECT Type, Location, MAX(Easting)
FROM CrimeData
GROUP BY Location, Type
HAVING Easting = MAX(Easting)
or simpler:
SELECT Type, Location, Easting
FROM CrimeData
where Easting = (select max(Easting) from CrimeData)
The column you use in the function (in your case MAX) should not be part of the group by statement.
Hopefully this clears it otherwise I can explain more ;)

Related

MAX in Select statement not returning the highest value?

I have a question regarding the max-statement in a select -
Without the MAX-statemen i have this select:
SELECT stockID, DATE, close, symbol
FROM ta_stockprice JOIN ta_stock ON ta_stock.id = ta_stockprice.stockID
WHERE stockid = 8648
ORDER BY close
At the end i only want to have the max row for the close-column so i tried:
Why i didnĀ“t get date = "2021-07-02" as output?
(i saw that i allways get "2021-07-01" as output - no matter if i use MAX / MIN / AVG...)
The MAX() turns the query into an aggregation query. With no GROUP BY, it returns one row. But the query is syntactically incorrect, because it mixes aggregated and unaggregated columns.
Once upon a time, MySQL allowed such syntax in violation of the SQL Standard but returned values from arbitrary rows for the unaggreged columns.
Use ORDER BY to do what you want:
SELECT stockID, DATE, close, symbol
FROM ta_stockprice JOIN ta_stock ON ta_stock.id = ta_stockprice.stockID
WHERE stockid = 8648
ORDER BY close DESC
LIMIT 1;

Is there a way to divide two halves of a boolean value in sql?

I'm currently working on a task where I'm dealing with a table in which every row has a boolean value, "is_important". I am trying to create a ratio of important entries to total entries grouped by date but I can't seem to get SQL to recognize that I want to divide using a WHERE clause.
One method is:
select date, avg( case when is_important then 1.0 else 0 end) as important_ratio
from t
group by date;
There may also be shortcuts, depending on the database you are using, such as:
avg( is_important )
avg( is_important::int )

SUM of database function returns much higher value than actual SUM

I have a database function that I am able to get the correct results from, but when I try to use SUM to total the results it returns a much higher value.
SELECT
SUM([DATABASE].[dbo].[fn_GetCharges]([TABLE1_DATE],[TABLE1_CUST],[TABLE1_SITE],[TABLE1_SERV])) AS [GROSS_REVENUE]
FROM [DATABASE].[dbo].[TABLE1]
WHERE
[TABLE1_ROUT] = '1234'
AND [TABLE1_DATE] = '2018-05-08'
This returns a SUM value of about 15,740.
If I remove the SUM and GROUP BY the function then it shows each of the returned values, which I manually totalled to about 750.
I'm using Microsoft SQL Server 2014.
We don't know what is in your function, but you could probably output your raw data first and then sum it next.
;WITH cte AS (
SELECT
[DATABASE].[dbo].[fn_GetCharges]([TABLE1_DATE],[TABLE1_CUST],[TABLE1_SITE],[TABLE1_SERV]) AS [GROSS_REVENUE]
FROM [DATABASE].[dbo].[TABLE1]
WHERE
[TABLE1_ROUT] = '1234'
AND [TABLE1_DATE] = '2018-05-08'
GROUP BY whatever_you_grouped_by_that_gave_correct_results
)
SELECT SUM(gross_revenue) AS gross_revenue
FROM cte
Wondering if you used group by clause in the query since I don't see one posted.
Group By (columns) Having (condition). What you specified in the 'where' goes in the 'Having' clause

"bad double value" in Google BigQuery

I'm working in Google BigQuery (not using LegacySQL), and I'm currently trying to cast() a string as a float64. Each time I get the error "Bad double value". I've also tried safe_cast() but it completely eliminates some of my id's (Ex: if one customer repeats 3 times for 3 different dates, and only has 'null' for a single "Height" entry, that customer is completely eliminated after I do safe_cast(), not just the row that had the 'null' value). I don't have any weird string value in my data, just whole or rational numbers or null entries.
Here's my current code:
select id, date,
cast(height as float64) as height,
cast(weight as float64) as weight
from (select id, date, max(height) as height, max(weight) as weight
from table
group by 1,2
)
group by 1, 2
Of course safe_cast() returns NULL values. That is because you have inappropriate values in the data.
You can find these by doing:
select height, weight
from table
where safe_cast(height) is null or safe_cast(weight) is null;
Once you understand what the values are, fix the values or adjust the logic of the query.
If you just want the max of values are are properly numeric, then cast before the aggregation:
select id, date,
max(safe_cast(height as float64)) as height,
max(safe_cast(weight as float64)) as weight
from table
group by 1, 2;
A subquery doesn't seem necessary or desirable for your query.

SQL code needed for Query

I need SQL code for a query I need to do in Access. I have a table with multiple fields but I only need 2 fields for the query. 1 is a date field. let's call that one DateField. the other is a field that contains text, let's call lit TextField. I need a query that returns the following:
The COUNT of DateField (i.e. how many there are regardless of what the value is)
The COUNT of TextField WHERE its value = "ThisText"
The COUNT of TextField WHERE its value = "ThatText"
Results GROUP BY Year
the same query again (will be a separate Q) but with results GROUP BY Month
Many thanks in advance for all your wonderful help.
I believe you can only SELECT a given aggregate function once per per query. That is to say you cannot request the COUNT two different fields in a single query. Here's the reference for the count function in JET SQL. At best you can count the number of non-NULL values of a certain field in a grouped result set under some WHERE clause.
SELECT YEAR/MONTH(DateField), COUNT(DateField),
SUM(IIF(TextField='ThisText', 1, 0)),
SUM(IIF(TextField='ThatText', 1, 0))
FROM MyTable
GROUP BY YEAR/MONTH(DateField)
How about:
SELECT
Year
,COUNT(DISTINCT DateField) AS NumDateFields
,COUNT(CASE WHEN TextField = 'ThisText' THEN 1 END) AS ThisTextCount
,COUNT(CASE WHEN TextField = 'ThatText' THEN 1 END) AS ThisTextCount
GROUP BY Year;
Or... GROUP BY Month