假设我有一个SQL查询
SELECT Label1, Label2, SUM(number) as MySum
FROM MyTable
GROUP BY Label1, Label2
它给了我一些像
的结果Label1 | Label2 | MySum
-------+--------+------
Foo | Bar | 100
Foo | Baz | -100
NotFoo | Bar | 100
NotFoo | Baz | -100
我可以使用WHERE
和HAVING
子句来过滤结果
SELECT Label1, Label2, SUM(number) as MySum
FROM MyTable
WHERE Label1 = 'Foo'
GROUP BY Label1, Label2
HAVING MySum > 0
这给了我结果
Label1 | Label2 | MySum
-------+--------+------
Foo | Bar | 100
WHERE
和HAVING
一起隐含AND
。
是否存在类似
的语法SELECT Label1, Label2, SUM(number) as MySum
FROM MyTable
WHERE Label1 = 'Foo'
GROUP BY Label1, Label2
OR HAVING MySum > 0
给出结果
Label1 | Label2 | MySum
-------+--------+------
Foo | Bar | 100
Foo | Baz | -100
NotFoo | Bar | 100
我能做到
SELECT Label1, Label2, SUM(number) as MySum
FROM MyTable
WHERE Label1 = 'Foo'
GROUP BY Label1, Label2
UNION
SELECT Label1, Label2, SUM(number)
FROM MyTable
GROUP BY Label1, Label2
HAVING MySum > 0
缺点:这可能效率低下,因为数据库必须两次计算Foo | Bar | 100
行,发现它是重复的,然后将其丢弃。
我也可以写
SELECT Label1, Label2, SUM(number) as MySum
FROM MyTable
WHERE Label1 = 'Foo'
GROUP BY Label1, Label2
UNION ALL
SELECT Label1, Label2, SUM(number)
FROM MyTable
WHERE Label1 <> 'Foo'
GROUP BY Label1, Label2
HAVING MySum > 0
缺点:乍一看开始变得不那么容易理解(可能是最不利的劣势)。
或者
SELECT Label1, Label2, SUM(number) as MySum
FROM MyTable
GROUP BY Label1, Label2
HAVING MySum > 0
OR Label1 = 'Foo'
缺点:这将使数据库可以完成大量非Foo
标签的额外工作。
答案 0 :(得分:1)
你最后的答案很好:
SELECT Label1, Label2, SUM(number) as MySum
FROM MyTable
GROUP BY Label1, Label2
HAVING MySum > 0
OR Label1 = 'Foo'
您已经说过这里有额外的工作,但事实并非如此,因为您必须进行汇总以找出非MySum>0
行的Label1='Foo'
以确定是否它们应该被包括在内。