SQL-只选择行

时间:2016-12-31 18:30:37

标签: sql sql-server

enter image description here

如图所示,有大量addressTypeID具有相同的Application ID和ValidTo Date行。

有时需要使用AddressTypeID作为返回列的条件。

我需要进行查询以获取带有AddressType的条件的validTo以及连接到applicationID的应用程序表中的一些细节:

SELECT APPLICATION_ID, FIRST_NAME, LAST_NAME
,MAIL_DATE = (SELECT VALIDTO FROM ADDRESS WHERE ADDRESSTYPEID = 1)

我需要输出只包含一行:

applicationid - firstname - lastname - validto
38  - John   - smith   - 2020-12-31 00:00:00.000
39  - Math   - Will    - 2015-09-23 00:00:00.000

没有让行重复。

4 个答案:

答案 0 :(得分:0)

JOIN通常比相关子查询表现更好。

如果application_idaddresstypeid组合是唯一的,那么只需:

SELECT t1.APPLICATION_ID,
  t1.FIRST_NAME,
  t1.LAST_NAME,
  t2.validto
FROM first_table t1
LEFT OUTER JOIN ADDRESS t2
ON t1.application_id = t2.application_id
AND t2.addresstypeid = 1;

如果没有,你可以这样做:

SELECT t1.APPLICATION_ID,
  t1.FIRST_NAME,
  t1.LAST_NAME,
  t2.validto mail_date
FROM first_table t1
LEFT OUTER JOIN
  (SELECT application_id,
    MAX(validto) validto
  FROM ADDRESS
  WHERE addresstypeid = 1
  GROUP BY application_id
  ) t2
ON t1.application_id = t2.application_id;

答案 1 :(得分:0)

您可以使用此


SELECT APPLICATION_ID, FIRST_NAME, LAST_NAME
,MAIL_DATE = (SELECT MAX(VALIDTO) FROM ADDRESS WHERE ADDRESSTYPEID = 1)

或者


SELECT APPLICATION_ID, FIRST_NAME, LAST_NAME
,MAIL_DATE = (SELECT Top 1 VALIDTO FROM ADDRESS WHERE ADDRESSTYPEID = 1 Order by ValidTo desc)

答案 2 :(得分:0)

试试这个,

SELECT * FROM Address WHERE ValidTo IS NOT NULL

OR

SELECT APPLICATION_ID, FIRST_NAME, LAST_NAME, Row FROM
(
    SELECT APPLICATION_ID, FIRST_NAME, LAST_NAME,
           ROW_NUMBER() 
           OVER(PARTITION BY Application_ID ORDER BY ValidTo) AS Row
    FROM Address
) tmp
WHERE tmp.Row = 1

答案 3 :(得分:0)

max(case when addTypeID =1 then addValidTo else '' end)