I need to choose among other fields the age of the client at the time when he bought a product of a certain brand, etc. WHERE the client was, for example, from 30 to 50 years old. He wrote this query (getAge just uses DATEDIFF to return age in years)
SELECT DISTINCT customers.FirstName, customers.LastName,
products.ProductName,
dbo.getAge(customers.BirthDate,sales.Datekey)
AS Age_when_buying
FROM sales
INNER JOIN dates ON sales.Datekey=dates.Datekey
INNER JOIN customers ON sales.CustomerKey=customers.CustomerKey
INNER JOIN products ON sales.ProductKey=products.ProductKey
INNER JOIN stores ON sales.StoreKey=stores.StoreKey
WHERE stores.StoreName = 'DribleCom Europe Online Store' AND
products.BrandName = 'Proseware' AND
dbo.getAge(customers.BirthDate, sales.Datekey) >= 30 AND
dbo.getAge(customers.BirthDate, sales.Datekey) <=50
and it works, but I calculate the age three times. I tried to assign age_when_buying to a variable, but that didn't work. My next thought was to use the cursor, but I feel that there is an easier way that I do not see. The question is, is this the right way to solve this problem, or what are my options?
source
share