Doing a calculation between two rows with EXTRA CRITERIA?
Name ExactDate Presents Location
bob1 2011 1 home
bob2 2008 2 school
bob2 2012 3 school
mary2 1986 4 school
mary1 2001 5 home
mary1 2012 6 home
kate1 2011 7 home
kate1 2012 8 home
kate2 2011 9 school
celia2 2011 10 school
celia2 1986 11 school
celia1 1972 12 home
celia1 2012 14 home
celia2 2012 13 school
This problem is done in SQL in MS Access 2003 for a query.
So the goal is we subtract the amount of presents kate got from celia on the same year ( b开发者_开发百科ut since there are a few different present values for the same year we choose to have priority of home > school....for example celia and kate both receive presents in 2012 but celia gets both home presents and school presents in 2012 in which case we choose her home present value to do the calculation) and out put should be something like the following:
Name ExactDate PresentsDiff
celiaminuskate 2011 3
celiaminuskate 2012 6
So far I have :
SELECT 'celiaminuskate'AS [NAME],T1.[date] AS [EXACT DATE],
T1.presents T2.presents AS [PRESENTS DIFF]
FROM Some_Table T1, Some_Table T2
part that I think needs to be fixed??
WHERE (T1.Name = 'celia1'>'celia2')
AND (T2.Name = 'kate1'>'kate2')
AND T2.ExactDate = T1.ExactDate
to indicate priority? I'm not too sure how to do it
ORDER BY T1.ExactDate
I created this query and saved it as qryCeliaAndKateGiftDates. It just returns the distinct ExactDate values for which celia and kate both had gifts recorded.
Notice I re-named your Name field to Recipient, because Name is a reserved word.
SELECT DISTINCT celia.ExactDate
FROM
[SELECT ExactDate
FROM Some_Table
WHERE Recipient Like "celia*"
]. AS celia
INNER JOIN [
SELECT ExactDate
FROM Some_Table
WHERE Recipient Like "kate*"
]. AS kate
ON celia.ExactDate = kate.ExactDate
ORDER BY celia.ExactDate;
Then I used correlated subqueries to return the correct Presents values for celia and kate on each of those ExactDates.
SELECT
raw.recipients AS [NAME],
raw.ExactDate AS [EXACT DATE],
(raw.celia_presents - raw.kate_presents) AS [PRESENTS DIFF]
FROM
[SELECT
'celiaminuskate' AS recipients,
dates.ExactDate,
(SELECT TOP 1 Presents
FROM Some_Table
WHERE
Recipient Like "celia*"
And ExactDate = dates.ExactDate
ORDER BY Location) AS celia_presents,
(SELECT TOP 1 Presents
FROM Some_Table
WHERE
Recipient Like "kate*"
And ExactDate = dates.ExactDate
ORDER BY Location) AS kate_presents
FROM qryCeliaAndKateGiftDates AS dates]. AS raw;
It returns the results you requested when run from Access 2003. However correlated subqueries are notoriously slow, so I'll be interested to see what other answers you get.
精彩评论