SQL - 按ID分组两列

时间:2016-04-29 08:04:39

标签: sql sas

我想用“ID”将两列“Immo”+“Conso”组合在一起,以便创建一个新变量“Mixte”。我的新变量“Mixte”如下:

  • 如果一个ID在“Immo”中有(至少)1,在“Conso”中有1,则“Mixte”为是,否则“Mixte”为否。

例如:

Ident   | Immo  | Conso | Mixte
---------------------------------
1       | 0     | 1     | yes
1       | 1     | 0     | yes
2       | 1     | 0     | no
3       | 0     | 1     | no
3       | 0     | 1     | no
3       | 0     | 1     | no
4       | 0     | 1     | yes
4       | 0     | 1     | yes
4       | 1     | 0     | yes

感谢您帮助我。如果我不清楚,请不要犹豫问我。

4 个答案:

答案 0 :(得分:4)

使用相关的子选择:

select t1.Ident, t1.Immo, t1.Conso,
       case when (select max(Immo) + max(Conso) from tablename t2
                  where t2.Ident = t1.Ident) = 2 then 'yes'
            else 'no'
       end as Mixte
from tablename t1

Ident是ANSI SQL中的保留字,因此您可能需要将其分隔为"Ident"

答案 1 :(得分:1)

它可能不是最平滑的方式,但我会这样做:

WebDriver driver= new ChromeDriver();
driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);
JavascriptExecutor js = (JavascriptExecutor)driver;

driver.get("http://imgur.com/");

final String JS_SCROLL_DOWN =
    "var callback = arguments[0], page = document.documentElement, height = page.scrollHeight; " +
    "window.scrollTo(0, height); " +
    "(function fn(){ " +
    "   if(page.scrollHeight != height && document.readyState == 'complete') " +
    "      return callback(); " +
    "   setTimeout(fn, 30); " +
    "})();";

js.executeAsyncScript(JS_SCROLL_DOWN);

答案 2 :(得分:1)

select ident,result=(case when sum(Immo)>0 and sum(Conso)>0 then 'yes' 
               else 'no' end)
from tabname (NOLOCK)
group by id

答案 3 :(得分:0)

SQL-Server 中,您可以尝试使用window functions,例如:

select Ident, Immo, Conso, 
       case when rn1 > 0 and rn2 > 0 then 'Yes' else 'No' end as Mixte
from (
    select
           max(Immo) over (partition by Ident) rn1,
           max(Conso) over (partition by Ident) rn2,
           *
    from table_name
)x