SQL - 选择+ MAx()

时间:2012-03-16 18:46:59

标签: sql join db2 max

我想在销售档案中将销售人员列表与该销售员的上次销售日期相结合。 请注意,销售人员可能尚未进行任何销售!

SELECT
    SLSNO,
    SLSNAME
FROM
    SALESMEN

SELECT
    SLSNO,
    max(SALEDATE)
FROM
    SALESHEADER
WHERE
    SALESMANNO = SLSNO
GROUP BY   
    SLSNO
ORDER BY
    SLSNO

使用ibm db2。如果可能的话,更喜欢标准的ANSI SQL。

1 个答案:

答案 0 :(得分:2)

如果他们尚未进行销售,则Latest Sale下面的第二种情况将为NULL

-- if you want all salesmen who have made a sale
SELECT
    SLSNO,
    SLSNAME,
    MAX(SALEDATE) AS [Latest Sale]
FROM
    SALESMEN AS s
JOIN
    SALESHEADER AS h
ON
    h.SLSNO = s.SLSNO
WHERE
    SALESMANNO = SLSNO
GROUP BY
    SLSNO,
    SLSNAME


-- if you want all salesmen even if they don't have a sale
SELECT
    SLSNO,
    SLSNAME,
    MAX(SALEDATE) AS [Latest Sale]
FROM
    SALESMEN AS s
LEFT OUTER JOIN
    SALESHEADER AS h
ON
    h.SLSNO = s.SLSNO
WHERE
    SALESMANNO = SLSNO
GROUP BY
    SLSNO,
    SLSNAME