我正在使用Microsoft SQL服务器。 以下查询生成一个类似于这样的表:
idnumber | checkID | taskID | status
1001 | 9000 | 410 | Approved
1001 | 9001 | 410 | Approved
1001 | 9002 | 410 | Approved
1201 | 9100 | 430 | Approved
1201 | 9101 | 430 | Approved
...而我需要的是只返回一个idnumber的查询,不管其他数据如何(因此只有一个idnumber被&#34;被批准&#34;而不是其他的)。< / p>
我希望的结果类似于:
idnumber | checkID | taskID |状态
1001 | 9000 | 410 |批准
1201 | 9100 | 430 |批准
到目前为止我的查询:
SELECT DISTINCT viewTable.idnumber
, viewTable.checkID
, viewTable.taskID
, 'Approved' AS status
FROM viewTable
INNER JOIN anotherTable
ON viewTable.idnumber = anotherTable.idnumber
INNER JOIN someOtherTable
ON someOtherTable.idnumber = anotherTable.idnumber
WHERE anotherTable.CODE = 'DesiredCode'
有关此问题的更多信息: 我在anotherTable.CODE中有一个特定的值,只想&#34;批准&#34;那个具体的代码。上面的查询批准了返回idnumber的任何内容。
答案 0 :(得分:1)
您可以使用max
或min
等聚合函数仅对一列中的唯一值感兴趣:
SELECT viewTable.idnumber
, MAX(viewTable.checkID) AS checkID
, MAX(viewTable.taskID) AS taskID
, 'Approved' AS status
FROM viewTable
INNER JOIN anotherTable
ON viewTable.idnumber = anotherTable.idnumber
INNER JOIN someOtherTable
ON someOtherTable.idnumber = anotherTable.idnumber
WHERE anotherTable.CODE = 'DesiredCode'
GROUP BY viewTable.idnumber
答案 1 :(得分:1)
一个简单的方法就是使用TOP 1获取第一行
SELECT TOP 1 DISTINCT viewTable.idnumber
, viewTable.checkID
, viewTable.taskID
, 'Approved' AS status
FROM viewTable
INNER JOIN anotherTable
ON viewTable.idnumber = anotherTable.idnumber
INNER JOIN someOtherTable
ON someOtherTable.idnumber = anotherTable.idnumber
WHERE anotherTable.CODE = 'DesiredCode'
最终通过正确的顺序