简体   繁体   English

如何使用CASE语句进行GROUP BY?

[英]How to GROUP BY with a CASE statement?

My SQL example is as follows... 我的SQL示例如下...

DECLARE @a TABLE(
    id INT,
    val BIT
);
INSERT INTO @a(id,val) VALUES (1,0),(2,0),(3,1),(4,0),(5,1);

SELECT
    id = CASE
        WHEN val = 1 THEN id
        ELSE MAX(id)
    END
FROM @a
WHERE val = 0
GROUP BY id, val;

What my result is: 我的结果是:

id
---
 1
 2
 4

What I am trying to get... 我想要得到的是...

id
---
 4

Or if I did "WHERE val = 1" then what I want is... 或者,如果我执行了“ WHERE val = 1”,那么我想要的就是...

id
---
 3
 5

What I'm basically trying to say is "if I'm selecting where val = 1, I want all the rows, but if I'm selecting where val = 0 I only want the row with the highest id". 我基本上想说的是“如果我选择val = 1,我想要所有行,但是如果我选择val = 0,我只希望id最大的行”。 Any ideas? 有任何想法吗?

I am not sure that I understand what you are trying to do, but the following query gives the expected result with WHERE val = 1 or WHERE val = 0 . 我不确定我是否了解您要尝试执行的操作,但是以下查询给出了WHERE val = 1WHERE val = 0的预期结果。 The idea is to move the case to the GROUP BY clause 想法是将案例移至GROUP BY子句

SELECT MAX(id)
FROM @a
WHERE val = 1
GROUP BY CASE WHEN val = 1 THEN id ELSE 0 END

You can use the UNION statement to combine tables. 您可以使用UNION语句合并表。 So if we split what you want to do into two select statements we get the following if the WHERE = 0 因此,如果将您要执行的操作分为两个选择语句,则在WHERE = 0的情况下,将得到以下内容

SELECT MAX(id) 
FROM @a
GROUP BY ID, VAL

UNION

SELECT ID
FROM @a
WHERE val = 0 AND val = 1
GROUP BY ID, VAL

And the following if the WHERE = 1 如果WHERE = 1,则以下内容

SELECT MAX(id) 
FROM @a
GROUP BY ID, VAL

UNION

SELECT ID
FROM @a
WHERE val = 1 AND val = 1
GROUP BY ID, VAL

This might make clear why changing the where clause to have it do something different seems strange to me. 也许可以弄清楚为什么更改where子句以使其具有不同的功能对我来说似乎很奇怪。 Clearly in the first one the part after the union is silly/useless. 显然,在第一个工会之后的部分是愚蠢的/无用的。 In the 2nd it also seems strange to have the same expression twice in the where clause. 在第二个中,在where子句中两次具有相同的表达式似乎也很奇怪。 But this meets your requirements to change one value in a where and have two different results. 但这满足您在某个位置更改一个值并产生两个不同结果的要求。

Maybe you can explain your requirements better now that you see the solution? 看到解决方案后,也许您可​​以更好地解释您的要求?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM