where 子句限制完全匹配的行,显示部分匹配的行
Posted
技术标签:
【中文标题】where 子句限制完全匹配的行,显示部分匹配的行【英文标题】:Where clause to restrict rows which are fully matched, show rows which are partially matched 【发布时间】:2021-01-22 11:56:12 【问题描述】:我有以下 SQL 查询:
SELECT
job.EngineeringJobNumber,
CASE
WHEN line.PMVoucherNumber IS NULL THEN 0
ELSE 1
END AS JobLinesMatched
FROM
Request_HDR hdr
JOIN
Request_LINE line ON hdr.RequestId = line.RequestId
JOIN
EngineeringJob job ON hdr.EngineeringJobId = job.EngineeringJobId
JOIN
GL00105 gl ON line.AccountIndex = gl.ACTINDX
WHERE
line.VendorID = 'Vendor' AND job.ApprovalStatus = 5
返回这个:
EngineeringJobNumber | JobLinesMatched |
---|---|
JOB00023 | 0 |
JOB00023 | 0 |
JOB00023 | 1 |
JOB00023 | 0 |
JOB00023 | 0 |
JOB00011 | 1 |
JOB00011 | 1 |
JOB00011 | 1 |
JOB00011 | 1 |
JOB00011 | 1 |
我想要实现的是限制工作行完全匹配的行,即该工作的所有行都是 1。
编辑:我仍然需要能够查看未完全匹配的作业的所有行,即 JOB0023 的所有 5 行。
我想我可能需要一个 HAVING 子句?任何帮助表示赞赏。
【问题讨论】:
能否分享示例数据? Why should I tag my DBMS 我有点迷路了。为什么要返回在所有行中具有相同值的两列?而且您的编辑完全混淆了这个问题。 【参考方案1】:你可以使用analytical function
如下:
select EngineeringJobNumber, JobLinesMatched from
(SELECT job.EngineeringJobNumber,
CASE WHEN line.PMVoucherNumber IS NULL THEN 0 ELSE 1 END AS JobLinesMatched
count(CASE WHEN line.PMVoucherNumber is NULL then 0 END)
over (partition by job.EngineeringJobNumber) as sm
FROM Request_HDR hdr
JOIN Request_LINE line ON hdr.RequestId = line.RequestId
JOIN EngineeringJob job ON hdr.EngineeringJobId = job.EngineeringJobId
JOIN GL00105 gl ON line.AccountIndex = gl.ACTINDX
WHERE line.VendorID = 'Vendor' AND job.ApprovalStatus = 5) t
WHERE sm > 0
【讨论】:
刚刚编辑了我的问题,因为我仍然需要返回未完全匹配的作业的所有行,包括匹配的行。但这让我更接近。 更新了答案。立即查看 感谢@Popeye,成功了!现在我要去阅读 PARTITION...以上是关于where 子句限制完全匹配的行,显示部分匹配的行的主要内容,如果未能解决你的问题,请参考以下文章