我有一个名为Business Entities“BE”的表和另一个名为Questionnaire“Q”的表,还有另一个名为“QBE”的表名称
表:BE
| BE_ID | Region | Name | Description |
| 1 | A | kl | ssss |
| 2 | A | dds | s saals |
| 3 | B | wf | ksd ks skd |
| 4 | B | dsc | sam sd ; |
表:Q
| Q_ID | Name | CreationDate |
| 1 | sce | 2014-01-01 |
| 2 | wcd | 2014-02-01 |
表:QBE
| QBE_ID | BE_ID | Q_ID |
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 2 |
现在我想从 BE 中选择所有不同的区域,其中 Q 的CreationDate是最新的。
我正在研究这些问题。第一次加入
| QBE_ID | BE_ID | Q_ID | Region | Name | Name | CreationDate |
| 1 | 1 | 1 | A | kl | sce | 2014-01-01 |
| 2 | 1 | 2 | A | dds | sce | 2014-02-01 |
| 3 | 2 | 2 | B | wf | wcd | 2014-02-01 |
然后由此我想选择
| QBE_ID | BE_ID | Q_ID | Region | Name | Name | CreationDate |
| 2 | 1 | 2 | A | dds | sce | 2014-02-01 |
| 3 | 2 | 2 | B | wf | wcd | 2014-02-01 |
对于所有区域“A”Q_ID“2”具有最新CreationDate的问卷,因此对于所有区域“B”,然后是所有其他区域。
到目前为止,这是我一直在做的事情,不要读它的复杂只是告诉我该怎么做。
SELECT BE.NAME00, QUES.ANSWER, QUES.DESCRIPTION, QT.CREATION_DATE
FROM OPAGES.RV_ENTITY AS BE,
OPAGES.RT__ENTITY_QUESTIONNAIRE AS EN_QT,
OPAGES.RV_QUESTIONNAIRE AS QT,
OPAGES.RT__QUESTIONNAIRE_QSECTION AS QT_SEC,
OPAGES.RT__QSECTION_QUEST AS SEC_QUES, OPAGES.RT_QUEST AS QUES
WHERE BE.ENTITY_ID = EN_QT.ENTITY_ID AND EN_QT.QUESTIONNAIRE_ID =
QT.QUESTIONNAIRE_ID
AND QT.QUESTIONNAIRE_ID = QT_SEC.QUESTIONNAIRE_ID
AND QT_SEC.QSECTION_ID = SEC_QUES.QSECTION_ID
AND SEC_QUES.QUEST_ID = QUES.QUEST_ID
AND QT.QUESTIONNAIRE_ID= (SELECT QT_SEC.QUESTIONNAIRE_ID
FROM OPAGES.RT__QUESTIONNAIRE_QSECTION AS QT_SEC,
OPAGES.RV_QUESTIONNAIRE AS QT
WHERE QT.QUESTIONNAIRE_ID = QT_SEC.QUESTIONNAIRE_ID
GROUP BY QT_SEC.QUESTIONNAIRE_ID, QT.CREATION_DATE
ORDER BY QT.CREATION_DATE DESC
FETCH FIRST ROW ONLY
)
GROUP BY QT.CREATION_DATE, QUES.DESCRIPTION, QUES.ANSWER, BE.NAME00
我在想像
SELECT *
FROM MyTable
WHERE (User, Date) IN
( SELECT User, MAX(Date) FROM MyTable GROUP BY User)
只是不能实现它
答案 0 :(得分:1)
根据创建日期为每个BE_ID,Q_ID组合生成行号。外部选择为每个集合BE_ID,Q_ID采用最新值。
SELECT * from
(
SELECT *, ROW_NUMBER() over ( partition by BE.BE_ID, Q.Q_ID order by Q.CreationDate desc) as seq
FROM BE
INNER JOIN QBE
ON BE.BE_ID = QBE.QBE_ID
INNER JOIN Q
ON Q.Q_ID = QBE.Q_ID
) T
WHERE T.seq =1
答案 1 :(得分:0)
完成,
SELECT *
FROM (
SELECT
EN_QT.ENTITY_ID,
QT.QUESTIONNAIRE_ID,
QT.CREATION_DATE AS CREATION_DATE
FROM
OPAGES.RV_QUESTIONNAIRE AS QT,
OPAGES.RT__ENTITY_QUESTIONNAIRE AS EN_QT
WHERE EN_QT.QUESTIONNAIRE_ID = QT.QUESTIONNAIRE_ID
GROUP BY
EN_QT.ENTITY_ID,
QT.QUESTIONNAIRE_ID,
QT.CREATION_DATE
)
WHERE (ENTITY_ID, CREATION_DATE)
IN (
SELECT
KILL.ENTITY_ID,
MAX(KILL.CREATION_DATE)
FROM (
SELECT
EN_QT.ENTITY_ID,
QT.QUESTIONNAIRE_ID,
QT.CREATION_DATE AS CREATION_DATE
FROM
OPAGES.RV_QUESTIONNAIRE AS QT,
OPAGES.RT__ENTITY_QUESTIONNAIRE AS EN_QT
WHERE
EN_QT.QUESTIONNAIRE_ID =QT.QUESTIONNAIRE_ID
GROUP BY
EN_QT.ENTITY_ID,
QT.QUESTIONNAIRE_ID,
QT.CREATION_DATE
) AS KILL
GROUP BY KILL.ENTITY_ID
)