我有一个约会数据库,每个人都有一个人格,序列号,约会日期和两个问卷评分。
我需要做的是每个人带回一行,显示他们的第一次约会,以及他们最后的约会,以及两者的得分。
我已经花了很长时间在一个非常简单的查询上,我已经尝试使用以下内容给我第一次约会分数:
SELECT
PERSONID,
MIN(CONTACTDATE) AS 'FIRST_CONTACT',
QUEST_1,
QUEST_2
FROM TBL_APPOINTMENTS
GROUP BY
PERSONID,
CONTACTDATE,
QUEST_1,
QUEST_2
ORDER BY
PERSONID,
FIRST_CONTACT
正如您可能猜到的那样,每次QUEST_1或QUEST_2中的值发生变化时,这都会给我重复的行。
有人可以帮忙吗?我确信这一切都非常简单,但却让我不得不在墙上!
提前致谢!
答案 0 :(得分:1)
使用 TypeError: theForm.submit is not a function
theForm.submit();
您可以按约ROW_NUMBER()
从1
开始为约会分配一个连续值。
在下面的例子中,我创建了两个这样的序数,一个是时间前进,另一个是时间倒退。然后我可以选择PERSONID
以及first going forward
。
first going backwards
编辑 将第一个和最后一个汇总到一行......
WITH
sorted AS
(
SELECT
PERSONID,
CONTACTDATE,
QUEST_1,
QUEST_2,
ROW_NUMBER() OVER (PARTITION BY PERSONID ORDER BY CONTACTDATE ASC) AS ORD_FWD,
ROW_NUMBER() OVER (PARTITION BY PERSONID ORDER BY CONTACTDATE DESC) AS ORD_REV
FROM
TBL_APPOINTMENTS
)
SELECT
PERSONID,
CONTACTDATE,
QUEST_1,
QUEST_2
FROM
sorted
WHERE
ORD_FWD = 1 OR ORD_REV = 1
ORDER BY
PERSONID,
CONTACTDATE
注意:第一次和最后一次约会可能是同一个约会(如果该人只有一次约会)。
答案 1 :(得分:1)
如果您要查找的结果是这样的:
PERSONID FIRST_CONTACT FIRST_QUEST_1 FIRST_QUEST_2 LAST_CONTACT LAST_QUEST_1 LAST_QUEST_2
----------- ------------- ------------- ------------- ------------ ------------ ------------
1 2015-01-01 10 11 2015-01-21 21 211
2 2015-01-01 11 24 2015-01-31 12 25
3 2015-02-01 13 21 2015-03-01 14 28
4 2015-03-01 15 29 2015-04-01 16 21
然后下面的查询会给你这个。请注意,如果一个人只有一条记录,则最大和最小日期和分数将相同。
SELECT
PERSONID,
FIRST_CONTACT, FIRST_QUEST_1, FIRST_QUEST_2,
LAST_CONTACT, LAST_QUEST_1, LAST_QUEST_2
FROM (
SELECT PERSONID, MIN(CONTACTDATE) AS 'FIRST_CONTACT', MAX(CONTACTDATE) AS 'LAST_CONTACT'
FROM TBL_APPOINTMENTS a
GROUP BY PERSONID
) a
CROSS APPLY (
SELECT QUEST_1 AS 'FIRST_QUEST_1', QUEST_2 AS 'FIRST_QUEST_2'
FROM TBL_APPOINTMENTS
WHERE PERSONID = a.PERSONID AND CONTACTDATE = A.FIRST_CONTACT
) o_first
CROSS APPLY (
SELECT QUEST_1 AS 'LAST_QUEST_1', QUEST_2 AS 'LAST_QUEST_2'
FROM TBL_APPOINTMENTS
WHERE PERSONID = a.PERSONID AND CONTACTDATE = A.LAST_CONTACT
) o_last
ORDER BY PERSONID, FIRST_CONTACT;
可以使用连接编写相同的查询:
SELECT
A.PERSONID,
FIRST_CONTACT,
F.QUEST_1 AS FIRST_QUEST_1,
F.QUEST_2 AS FIRST_QUEST_2,
LAST_CONTACT,
L.QUEST_1 AS LAST_QUEST_1,
L.QUEST_2 AS LAST_QUEST_2
FROM (
SELECT PERSONID, MIN(CONTACTDATE) AS 'FIRST_CONTACT', MAX(CONTACTDATE) AS 'LAST_CONTACT'
FROM TBL_APPOINTMENTS a
GROUP BY PERSONID
) a
JOIN TBL_APPOINTMENTS F ON F.PERSONID = a.PERSONID AND A.FIRST_CONTACT = F.CONTACTDATE
JOIN TBL_APPOINTMENTS L ON L.PERSONID = a.PERSONID AND A.LAST_CONTACT = L.CONTACTDATE
ORDER BY A.PERSONID, FIRST_CONTACT;
答案 2 :(得分:0)
SELECT PERSONID,
MIN(CONTACTDATE) AS 'FIRST_CONTACT', MAX(CONTACTDATE) AS 'LAST_CONTACT'
QUEST_1,
QUEST_2
FROM TBL_APPOINTMENTS
GROUP BY PERSONID,
CONTACTDATE,
QUEST_1,
QUEST_2
ORDER BY
PERSONID,
FIRST_CONTACT