SQL MAX,更多联接和位置

时间:2019-01-17 08:33:39

标签: sql

我试图找到其他问题的解决方案,但还没有走运。 所以我这样尝试: 我有3张桌子:

表:w_header:

|event_perfno_i|state|reg |issue_date|closing_date|
|--------------|-----|----|----------|------------|
|1111111       |C    |AAA |13-1-2019 |13-1-2019   |
|1111112       |C    |AAA |14-1-2019 |14-1-2019   |
|1111113       |C    |BBB |14-1-2019 |14-1-2019   |
|1111114       |C    |CCC |13-1-2019 |13-1-2019   |
|1111115       |C    |CCC |14-1-2019 |14-1-2019   |

表:w_header_crx

|event_perfno_i|check|
|--------------|-----|
|1111111       |Y    |
|1111112       |Y    |
|1111113       |Y    |
|1111114       |Y    |
|1111115       |Y    |

表ac:

|reg    |oper   |status|
|-------|-------|------|
|AAA    |CLK    |0     |
|BBB    |CLK    |0     |
|CCC    |CLK    |0     |
|DDD    |CLK    |0     |
|EEE    |CLK    |0     |

随着显示所需字段并在下面使用,查询其工作正常。但是,如果我添加其他字段,结果将不正确,并且显示的记录太多。

SELECT w_header.reg, MAX(w_header.event_perfno_i) AS WO
FROM w_header
LEFT JOIN ac ON w_header.reg = ac.reg
JOIN w_header_crx ON w_header_crx.event_perfno_i =   w_header.event_perfno_i
WHERE (ac.ac_typ IN ('E17', 'E19'))
AND ac.oper = 'CLK'
AND w_header.state = 'C'
AND w_header_crx.check = 'Y'
GROUP BY 
w_header.reg
ORDER BY w_header.reg

尽管有条件,但SQL确实提供了应有的更多记录。

预期输出应为:

|event_perfno_i|reg |issue_date |closing_date|
|--------------|----|-----------|------------|
|1111112       |AAA |14-1-2019  |14-1-2019   |
|1111113       |BBB |14-1-2019  |14-1-2019   |
|1111115       |CCC |14-1-2019  |14-1-2019   |

希望我的愿望很清楚,谢谢。

1 个答案:

答案 0 :(得分:0)

如果只希望AC存在,则应使用INNER JOIN而不是LEFT JOIN

SELECT w_header.reg, MAX(w_header.event_perfno_i) AS WO
FROM w_header
INNER JOIN ac ON w_header.reg = ac.reg
INNER JOIN w_header_crx ON w_header_crx.event_perfno_i =   w_header.event_perfno_i
WHERE (ac.ac_typ IN ('E17', 'E19'))
AND ac.oper = 'CLK'
AND w_header.state = 'C'
AND w_header_crx.check = 'Y'
GROUP BY  w_header.reg
ORDER BY w_header.reg