使用WHERE语句为每个ID选择一行

时间:2015-11-19 09:12:31

标签: mysql sql oracle

我目前正在编写一个SQL语句,在满足要求时,每个ID只能选择一行。

我假设表COMPONENTS看起来像这样:

COMP_ID  DATE_FROM  TIMESTAMP  COMP_TRX_ID
1        10-JAN-14  10-JAN-15  5
1        10-JAN-15  10-JAN-14  5
1        10-JAN-12  10-JAN-13  5
1        11-JAN-16  10-JAN-12  5
2        11-JAN-14  10-JAN-15  5
2        11-JAN-15  10-JAN-14  5
2        11-JAN-12  10-JAN-13  5
2        11-JAN-16  10-JAN-12  5

现在让我们假设表NEXT_DATE中的COMPONENT_STATUS01-JAN-15

这是我目前写的SELECT声明。

SELECT * FROM (SELECT c.* FROM
COMPONENTS c,
COMPONENTS_TRX ct
WHERE 1=1
AND ct.NAME = 'COMP_77C'
AND c.COMP_ID = ct.COMP_ID
AND c.COMP_ID IN (1,2)
AND trunc(c.DATE_FROM) < (SELECT trunc(ADD_MONTHS((NEXT_DATE),1)) FROM (SELECT NEXT_DATE FROM COMPONENT_STATUS
WHERE COMP_REF_CODE = (SELECT ID FROM REF_CODE WHERE CODE = 'COMP_ACTUAL')
ORDER BY NEXT_DATE DESC)
WHERE ROWNUM = 1
))
ORDER BY DATE_FROM DESC, COMP_TIMESTAMP DESC, COMP_TRX_ID DESC
;

它会从表格COMPONENT返回所有内容,但正确排序。

如何使输出看起来像这样:

COMP_ID  DATE_FROM  TIMESTAMP  COMP_TRX_ID
1        10-JAN-15  10-JAN-14  5
2        11-JAN-15  10-JAN-14  5

仅包含符合要求的第一行?

1 个答案:

答案 0 :(得分:1)

您可以使用分组和聚合功能,具体取决于您的需求(如MAX):

SELECT  COMP_ID,  MAX(DATE_FROM) AS DATE_FROM,
        MAX(TIMESTAMP) AS TIMESTAMP,  MAX(COMP_TRX_ID) AS COMP_TRX_ID
FROM (SELECT c.* 
      FROM
        COMPONENTS c,
        COMPONENTS_TRX ct
      WHERE 1=1
         AND ct.NAME = 'COMP_77C'
         AND c.COMP_ID = ct.COMP_ID
         AND c.COMP_ID IN (1,2)
         AND trunc(c.DATE_FROM) < (SELECTtrunc(ADD_MONTHS((NEXT_DATE),1)) 
                                  FROM (SELECT NEXT_DATE FROM COMPONENT_STATUS
                                  WHERE COMP_REF_CODE = (SELECT ID 
                                                         FROM REF_CODE 
                                                          WHERE CODE = 'COMP_ACTUAL')
      ORDER BY NEXT_DATE DESC)
WHERE ROWNUM = 1
))
GROUP BY COMP_ID
ORDER BY DATE_FROM DESC, COMP_TIMESTAMP DESC, COMP_TRX_ID DESC;

还要尝试避免使用逗号连接语法(已过时)并使用JOIN

FROM COMPONENTS c,
     COMPONENTS_TRX ct

为:

FROM COMPONENTS c
JOIN COMPONENTS_TRX ct
  ON c.COMP_ID = ct.COMP_ID