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
此问题在MS Access 2003中用于查询的SQL中完成。
所以我们的目标是减去凯特在同一年从凯里亚那里得到的礼物数量(但由于同年有几个不同的现值,我们选择优先考虑家庭>学校....例如,西莉亚和凯特都在2012年收到礼物,但西莉亚在2012年获得了家居礼物和学校礼物,在这种情况下我们选择她的家庭现值来进行计算)并且外出应该是如下:
Name ExactDate PresentsDiff
celiaminuskate 2011 3
celiaminuskate 2012 6
到目前为止,我有:
SELECT 'celiaminuskate'AS [NAME],T1.[date] AS [EXACT DATE],
T1.presents T2.presents AS [PRESENTS DIFF]
FROM Some_Table T1, Some_Table T2
部分我认为需要修复?
WHERE (T1.Name = 'celia1'>'celia2')
AND (T2.Name = 'kate1'>'kate2')
AND T2.ExactDate = T1.ExactDate
表示优先顺序?我不太清楚该怎么做
ORDER BY T1.ExactDate
答案 0 :(得分:1)
我创建了这个查询并将其保存为qryCeliaAndKateGiftDates。它只返回不同的ExactDate值,其中celia和kate都记录了礼物。
注意我将名称字段重命名为收件人,因为名称是保留字。
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;
然后我使用相关子查询在每个ExactDates上为celia和kate返回正确的Presents值。
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;
它返回从Access 2003运行时请求的结果。但是相关的子查询非常慢,所以我很想知道你得到的其他答案。