sql - Using a current row value into a subquery -


i trying count how many times order_id appears in subquery , present right next average value of each customer orders. here have tried.

select person ,avg(ordertotal) avgordersvalue , timesseen       ( select   customer_id person  ,order_id , sum(total)as ordertotal  ,(select count(order_id) timesseen   orders  customer_id=person  group order_id     ) orders group customer_id  order_id order person ) tablealias  group person  

and here message get: "msg 207, level 16, state 1, line 4 invalid column name 'person'. msg 8155, level 16, state 2, line 10 no column name specified column 4 of 'gg'. msg 207, level 16, state 1, line 1 invalid column name 'timesseen'."

based on description, may query want:

select person, avg(ordertotal), count(distinct orderid) (select customer_id person, order_id, sum(total) ordertotal       orders       group customer_id, order_id      ) o group person  

i "may" because expect orderid unique key in orders table. so, inner subquery wouldn't doing anything. perhaps mean orderlines in inner query.

the reason query fails because of correlation statement:

where customer_id = person 

you intend use value outer query ("person") relate inner 1 ("customer_id"). however, inner query not know alias in select clause of outer one. so, "person" undefined. when doing correlated subqueries, should always use table aliases. query should more like:

(select count(o2.order_id) timesseen    orders o2  o2.customer_id=o.person   group o2.order_id ) 

assuming "o" alias orders in outer query. correlated subqueries not needed. should simplify query.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -