我的SQL查询如下:
SELECT *
FROM table
WHERE criteria = 1
ORDER BY group;
我明白了:
group | value | criteria
------------------------
A | 0 | 1
A | 1 | 1
B | 2 | 1
B | 3 | 1
但是,我想将结果限制为仅第一组(在本例中为A)。即,
group | value | criteria
------------------------
A | 0 | 1
A | 1 | 1
SELECT *
FROM table
WHERE criteria = 1
GROUP BY group;
我可以使用GROUP BY
子句聚合组,但这会给我:
group | value
-------------
A | 0
B | 2
或EACH组的某些聚合函数。但是,我不想聚合行!
我也可以通过子查询指定组:
SELECT *
FROM table
WHERE criteria = 1 AND
group = (
SELECT group
FROM table
WHERE criteria = 1
ORDER BY group ASC
LIMIT 1
);
这样可行,但与往常一样,子查询很混乱。特别是,这需要两次为WHERE
指定criteria
条款。当然必须有一个更清洁的方法来做到这一点。
答案 0 :(得分:1)
您可以尝试以下查询: -
SELECT *
FROM table
WHERE criteria = 1
AND group = (SELECT MIN(group) FROM table)
ORDER BY value;
答案 1 :(得分:1)
如果您的数据库支持WITH子句,请尝试此操作。它与使用子查询类似,但您只需要指定一次<button class="button" type="button" ng-click="window.open(url, '_system', 'location=yes'); return false;">
open
</button>
输入。它也更容易理解发生了什么。
criteria
答案 2 :(得分:0)
使用DENSE_RANK()
DECLARE @yourTbl AS TABLE (
[group] NVARCHAR(50),
value INT,
criteria INT
)
INSERT INTO @yourTbl VALUES ( 'A', 0, 1 )
INSERT INTO @yourTbl VALUES ( 'A', 1, 1 )
INSERT INTO @yourTbl VALUES ( 'B', 2, 1 )
INSERT INTO @yourTbl VALUES ( 'B', 3, 1 )
;WITH cte AS
(
SELECT i.* ,
DENSE_RANK() OVER (ORDER BY i.[group]) AS gn
FROM @yourTbl AS i
WHERE i.criteria = 1
)
SELECT *
FROM cte
WHERE gn = 1
group | value | criteria
------------------------
A | 0 | 1
A | 1 | 1