Query

如果值等於另一列中的值,則禁止在列中顯示

  • October 30, 2018

我有 2 個並排顯示的日期列。我有一些相同的日期。我不想在其中一列中顯示“相等”的日期/重複的日期值。

例子:

   column1     column2
   1-1-2014    1-1-2014

我想顯示:

   column1     column2
   1-1-2014          

我該如何做到這一點?

請參閱下面的 DDL、DML 和 SQL,它應該為您提供一些(全部?)的方法。它取自 MySQL,但應該是相當通用的。

看看這個(MS SQL Server)和這個(更一般的)。檢查您的特定伺服器的 docco 是否有任何或所有可能適用的內容。

CREATE TABLE fred 
(
 billy int(11) DEFAULT NULL,
 d1 date DEFAULT NULL,
 d2 date DEFAULT NULL
);

mysql> desc fred;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| billy | int(11) | YES  |     | NULL    |       |
| d1    | date    | YES  |     | NULL    |       |
| d2    | date    | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> insert into fred values(1, '20140606', '20140607');
Query OK, 1 row affected (0.09 sec)

mysql> insert into fred values(1, '20140606', '20140606');  <<<=== SAME
Query OK, 1 row affected (0.07 sec)

mysql> insert into fred values(1, '20140607', '20140608');
Query OK, 1 row affected (0.06 sec)

mysql> select * from fred;
+-------+------------+------------+
| billy | d1         | d2         |
+-------+------------+------------+
|     1 | 2014-06-06 | 2014-06-07 |
|     1 | 2014-06-06 | 2014-06-06 |  <<=== SAME
|     1 | 2014-06-07 | 2014-06-08 |
+-------+------------+------------+
3 rows in set (0.00 sec)

SELECT billy, d1, 
 CASE
   WHEN d1 = d2 
     THEN NULL
   ELSE 
     d2
 END AS d2 
FROM fred;

+-------+------------+------------+
| billy | d1         | d2         |
+-------+------------+------------+
|     1 | 2014-06-06 | 2014-06-07 |
|     1 | 2014-06-06 | NULL       | <<== ***
|     1 | 2014-06-07 | 2014-06-08 |
+-------+------------+------------+ 

考慮到您的表格名稱是“date_table”,那麼您可以像這樣選擇

SELECT date_table1.`column1`, date_table2.`column2`
FROM date_table AS date_table1
LEFT JOIN date_table AS date_table2 
                    ON date_table1.`column1` = date_table2.`column1` 
                    AND date_table1.`column2` = date_table2.`column2` 
                    AND date_table1.`column1` != date_table2.`column2`

引用自:https://dba.stackexchange.com/questions/73450