I'm doing a summary table where I am creating a new table aggregating by average. Tiny example shown here:
CREATE TABLE PURCHASES (U_ID INT, TIMECODE TINYINT, PURCHASEVALUE INT);
INSERT INTO PURCHASES VALUES
(3399, 1, 10), (3399, 2, 20),
(2222, 2, 20), (2222, 2, 30),
(6644, 1, 10), (6644, 1, 30), (6644, 3, 10), (6644, 2, 60),
(4000, 4, 399);
CREATE TABLE PURCHASES_BY_TIMECODE
SELECT TIMECODE, AVG(PURCHASEVALUE) AS AVG_PURCHASEVALUE
FROM PURCHASES
GROUP BY PURCHASES.TIMECODE;
I get the warning error message "Data truncated for column AVG_PURCHASEVALUE". When I look at the data types of my new table, I see:
TIMECODE tinyint(4)
AVG_PURCHASEVALUE decimal(14,4)
My guess is that the avg function is returning something that doesn't fit into the decimal(14, 4) that mysql has invented for the data type of the 2nd column.
The results look sensible but I would prefer to code it up so that I didn't get this error. I think that what I need to do is either (a) explicitly specify the column data type for my table which I now do with a create/select, or (b) round the average with zero decimals so it fits into int and I avoid data type issues by ducking them.
Two problems with approach (a):
1. I am not sure how to define the column data type via a create/select statement - or whether this is even possible to do, syntactically - the only uses I've run into of create/select don't explicitly declare column types
- assuming I can find a suitable syntax for declaring the type, I am not sure what type to cast it into so that the error will go away and the result of the avg computation will be of the same type, as I am not sure what this type is, or whether it can be specified somehow in the function
Two questions:
- Is approach b the most fit for purpose for me in this circumstance? In this instance I don't actually care about decimal points. (But in some other use case I might.)
- How would I go about doing approach a? (in case it fits some other scenario I run into in future)
thanks!
p.s. needless to say, I am new to sql...
Aucun commentaire:
Enregistrer un commentaire