SQL: is my syntax correct?
q1: given a table : ID, Date, Status. Write a SQL query which receives @ID @Date and retrieve the status the person with that id on that date or the last status before that date if that date doesn't exist.
q2: given a table : ID, Date, Money. Write a SQL query which retriev开发者_如何学Pythone the average money amount for the dates that appears in the table.
i.e. for the following table the average is 600/2 (there are two different dates)
ID1 1/1/2010 100
ID2 1/1/2010 300
ID2 2/1/2010 200
I have tried to write queries for above questions. I would appreciate you remarks:
Answer 1
SELECT TOP 1 status from MyTable AS T
WHERE T.Date <= @date && T.id = @id
ORDER BY T.Date
Answer 2
declare money_sum decimal
declare days_count int
money_sum =
SELECT SUM(MONEY) FROM table_name
days_count =
SELECT DISTINCT COUNT(date) FROM table_name
return money_sum/ days_count
The syntax, would depend on the rdbms you're using, i'm assuming MSSQL, or possibly sybase, based on the TOP syntax you've used, in which case, you'll need to use @ in front of your variables, and the set keyword:
declare @money_sum decimal
declare @days_count int
set @money_sum = SELECT SUM(MONEY) FROM table_name
set @days_count = SELECT COUNT(DISTINCT date) FROM table_name
return @money_sum/ @days_count
Notice how i also moved the distinct inside the count function.
精彩评论