Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

sql - Find average ID then fetch data with same ID from another table

I need to find the average grid_id in the client table then fetch x and y from the grid table with the corresponding id. I have tried this query here:

SELECT round(AVG(client_id)) as testyy, grid.x,grid.y 
FROM client
JOIN grid
ON client.grid_id = grid.grid_id
WHERE grid.grid_id = AVG(client_id)
group by GRID.X,GRID.Y

but cant seem to get it to work.

DESIRED OUTPUT: average grid location

EXAMPLE DATA: grid table

INSERT INTO grid (x,y) values (-10,-10);
INSERT INTO grid (x,y) values (-10,-9);
INSERT INTO grid (x,y) values (-10,-8);
INSERT INTO grid (x,y) values (-10,-7);
INSERT INTO grid (x,y) values (-10,-6);
INSERT INTO grid (x,y) values (-10,-5);
INSERT INTO grid (x,y) values (-10,-4);

EXAMPLE DATA: CLIENT TABLE

INSERT INTO client (name,payment_method,grid_id,service_id) VALUES ('Derri','cash',563,57);
INSERT INTO client (name,payment_method,grid_id,service_id) VALUES ('Eil','card',616,758);
INSERT INTO client (name,payment_method,grid_id,service_id) VALUES ('Sid','cash',595,59);
INSERT INTO client (name,payment_method,grid_id,service_id) VALUES ('Amelia','card',601,60);
INSERT INTO client (name,payment_method,grid_id,service_id) VALUES ('Lewis','card',479,61);
INSERT INTO client (name,payment_method,grid_id,service_id) VALUES ('Mel','card',480,62);
INSERT INTO client (name,payment_method,grid_id,service_id) VALUES ('Gordon','card',480,63);
INSERT INTO client (name,payment_method,grid_id,service_id) VALUES ('Gino','card',479,64);
question from:https://stackoverflow.com/questions/65849112/find-average-id-then-fetch-data-with-same-id-from-another-table

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Find average ID then fetch data with same ID from another table

Maybe a subquery will do the trick. Try:

select x, y
from grid
where id = ( 
  select round( avg( grid_id ) )
  from client 
) ;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...