我是SQL(Oracle)的新手,我正在尝试编写一个声明,如果Parent1和Parent2地址不同,那么我希望Parent2在下一行插入相同的学生信息。第一部分(在底部部分(FROM,WHERE,GROUP)的CASE语句之前单独工作,但是如果它与Parent1不同,我想在Parent2信息中。
谢谢!
SELECT
MAX(STUDENTS.LAST_NAME) AS LASTNAME,
MAX(US.GUARDIAN1_FIRSTNAME || ' ' || US.GUARDIAN1_LASTNAME) AS PARENT1,
MAX(US.GUARDIAN2_FIRSTNAME || ' ' || US.GUARDIAN2_LASTNAME) AS PARENT2,
MAX(US.GUARDIAN1_ADDRESSSTREET) AS PARENTADDRESS
CASE
WHEN (MAX(US.GUARDIAN1_ADDRESSSTREET) <> MAX(US.GUARDIAN2_ADDRESSSTREET)
INSERT (MAX(STUDENTS.LAST_NAME) AS LASTNAME,
MAX(' ' || ' ') AS PARENT1,
MAX(US.GUARDIAN2_FIRSTNAME || ' ' || US.GUARDIAN2_LASTNAME) AS PARENT2,
MAX(US.GUARDIAN2_ADDRESSSTREET)
FROM
STUDENTS,
U_STUDENTSUSERFIELDS US
WHERE
US.studentsdcid = students.dcid
AND STUDENTS.ENROLL_STATUS = 0
AND STUDENTS.ENROLLMENT_SCHOOLID = 340
GROUP BY
STUDENTS.FAMILY_IDENT
我希望它看起来像这样:
==============================================================================
| LASTNAME | PARENT1 | PARENT2 | PARENTADDRESS |
==============================================================================
| Smith | Jane Doe | John Smith | 1818 Street |
------------------------------------------------------------------------------
| Smith | | John Smith | 2525 Other Street |
------------------------------------------------------------------------------
| Jones | Alice Jones | Mike Jones | 111 Old Street |
------------------------------------------------------------------------------
| Johnson | Perl Johnson | Bob Johnson | 222 Sesame Street |
------------------------------------------------------------------------------
| Apples | Eddy Apples | Sally Apples | 555 Street |
------------------------------------------------------------------------------
| Apples | | Sally Apples | 333 Helpme Ave. |
==============================================================================
答案 0 :(得分:0)
我认为这对你有用:
INSERT INTO targettable
(
LASTNAME,
PARENT1,
PARENT2,
PARENTADDRESS
)
SELECT
LASTNAME,
PARENT1,
PARENT2,
PARENTADDRESS
FROM
(
SELECT
s1.LASTNAME AS LASTNAME,
s1.PARENT1 AS PARENT1,
s1.PARENT2 AS PARENT2,
s1.PARENTADDRESS1 AS PARENTADDRESS
FROM
sourcetable AS s1
UNION
SELECT
s2.LASTNAME AS LASTNAME,
NULL AS PARENT1,
s2.PARENT2 AS PARENT2,
s2.PARENTADDRESS2 AS PARENTADDRESS
FROM
sourcetable AS s2
WHERE
s2.PARENTADDRESS1 = s2.PARENTADDRESS2
) AS z
ORDER BY
LASTNAME
PARENT2