条件SQL Where子句返回不同的行

时间:2019-07-18 08:14:04

标签: sql sql-server

具有以下值的SQL表

  <head>
    <meta charset="utf-8">
    <title>Minehype | Adminlogin</title>
    <link rel="stylesheet" href="../../css/adminlogin.css">
  </head>
  <body>
    <?php
    if(isset($_POST["submit"])) {
      require("mysql.php");
      $stmt = $mysql->prepare("SELECT * FROM accounts WHERE USERNAME = :user");
      $stmt->bindParam(":user", $_POST["username"]);
      $stmt->execute();
      $count = $stmt->rowCount();
      if($count == 0) {
        $row = $stmt->fecth();
        if(password_verify($_POST["password"], $row["PASSWORD"])) {
          session_start();
          $_SESSION["benutzer"] = $row["USERNAME"];
          header("Location: geheim.php");
        } else {
          echo "Der Login ist Fehlgeschlagen!";
        }

    } else {
      echo"Der Login ist fehlgeschlagen!"
    }
  }
    ?>
    <form class="box" action="" method="post">
      <h1> Admin Login </h1>
      <form action="adminlogin.php" method="post">
        <input type="benutzer" name="" placeholder="Benutzername">
        <input type="password" name="" placeholder="Passwort">
        <input type="submit" name="" value="Login">
      </form>
    </form>
  </body>

我喜欢为每个employeeId返回一个ID,该ID仅首先存在NULL CompletionDate。如果没有NULL日期,但之后是CompletionDate NOT NULL。

预期结果

Id, EmployeeId, CompletionDate  
1,   100,        NULL  
2,   100,        1/1/2019  
3,   101,        NULL  
4,   102,        1/1/2019  

where子句看起来像什么?

2 个答案:

答案 0 :(得分:2)

您可以尝试将ROW_NUMBER窗口功能与CASE WHEN Order by

一起使用

查询1

SELECT EmployeeId,CompletionDate
FROM (
    select *,ROW_NUMBER() OVER(PARTITION BY EmployeeId ORDER BY CASE WHEN CompletionDate IS NULL THEN 0 ELSE 1 END) rn
    from T 
) t1
where rn = 1

Results

| EmployeeId | CompletionDate |
|------------|----------------|
|        100 |         (null) |
|        101 |         (null) |
|        102 |       1/1/2019 |

答案 1 :(得分:0)

另一种方法使用not exists

select t.*
from t
where t.CompletionDate is null or
      not exists (select 1 
                  from t t2
                  where t2.EmployeeId = t.EmployeeId and
                        t2.CompletionDate is null
                 );

或聚合:

select EmployeeId,
       (case when count(*) = count(CompletionDate)  -- no nulls
             then max(CompletionDate)
        end) as CompletionDate
from t
group by EmployeeId;
相关问题