SQL查询让我感到困惑

时间:2018-11-02 20:31:12

标签: sql-server tsql select

这是我的情况:我有两个表,表A有列:

  ID,
  Name,
  ClassYear,
  Classmonth

ID是主键,没有重复。

表b包含以下列:

    ID,
    addresstype
    addline1
    addline2
    country,
    city,
    state,
    zip

IDtable B中不是唯一的,但这是您链接回table A的方式。

如果您有多个address,例如Homeschool,那么您在table b中的记录已超过记录。

我的任务是从table A中选择class year>= 2019的所有人,并选择class year = 2018class month的所有人。 >=5

我没问题。

现在让我感到困惑的是,我有来自table A的人员列表,我需要查询table b,而我只想提取同时拥有homeschool地址类型和地址相同,例如line 1line 2countrycitystatezip都是相同的。

我将不胜感激。

2 个答案:

答案 0 :(得分:3)

您可以按地址的详细信息分组并计算其具有的不同类型的数量:

SELECT *
FROM   table1
WHERE  id IN (SELECT   id
              FROM     table2
              WHERE    addresstype IN ('home', 'school')
              GROUP BY id, addline1, addline2, country, city, state, zip
              HAVING   COUNT(DISTINCT addresstype) = 2)

答案 1 :(得分:1)

SELECT
    DISTINCT
    student.ID
    , student.Name
    , student.ClassYear
    , student.ClassMonth
FROM
    TableA AS student
    INNER JOIN TableB AS homeAddress ON
        student.ID = homeAddress.ID
        AND homeAddress.addressType = 'Home'
    INNER JOIN TableB AS schoolAddress ON
        student.ID = schoolAddress.ID
        AND schoolAddress.addressType = 'School'
        AND homeAddress.line1 = schoolAddress.line1
        AND homeAddress.line2 = schoolAddress.line2
        AND homeAddress.country = schoolAddress.country
        AND homeAddress.city = schoolAddress.city
        AND homeAddress.state = schoolAddress.state
        AND homeAddress.zip = schoolAddress.zip
WHERE
    student.classYear >= 2019
    OR (student.ClassYear = 2018 AND student.classMonth >= 5)
;