表模式:複雜的SQL SELECT查詢
CREATE TABLE TRANSACTIONDETAILS
(
TransNo CHAR(15),
Serial INT,
Project CHAR(3)
)
數據集:
+-----------------+--------+---------+
| TransNo | Serial | Project |
+-----------------+--------+---------+
| A00000000000001 | 1 | 100 |
| A00000000000001 | 2 | 101 |
| A00000000000002 | 1 | 100 |
| A00000000000002 | 2 | 101 |
| A00000000000003 | 1 | 100 |
| A00000000000003 | 2 | 200 |
| A00000000000004 | 1 | 200 |
| A00000000000004 | 2 | 100 |
| A00000000000005 | 1 | 101 |
| A00000000000005 | 2 | 100 |
+-----------------+--------+---------+
我想,以確定這些交易有同一個項目組。
預期輸出:
+-----------------+--------+---------+---------+
| TransNo | Serial | Project | Flag |
+-----------------+--------+---------+---------+
| A00000000000001 | 1 | 100 | 1 |
| A00000000000001 | 2 | 101 | 1 |
| A00000000000002 | 1 | 100 | 1 |
| A00000000000002 | 2 | 101 | 1 |
| A00000000000005 | 1 | 101 | 1 |
| A00000000000005 | 2 | 100 | 1 |
| A00000000000003 | 1 | 100 | 2 |
| A00000000000003 | 2 | 200 | 2 |
| A00000000000004 | 1 | 200 | 2 |
| A00000000000004 | 2 | 100 | 2 |
+-----------------+--------+---------+---------+
我使用SQL Server 2012及更高版本。
謝謝。
UPDATE 1:如果我從輸入數據集中獲得以下內容,我的部分目標就會實現。
+-----------------+---------+---------+
| TransNo | Project1| Project2|
+-----------------+---------+---------+
| A00000000000001 | 100 | 101 |
| A00000000000002 | 100 | 101 |
| A00000000000003 | 100 | 200 |
| A00000000000004 | 200 | 100 |
| A00000000000005 | 101 | 100 |
+-----------------+---------+---------+
更新2:
數據集
+-----------------+--------+---------+
| TransNo | Serial | Project |
+-----------------+--------+---------+
| A00000000000001 | 1 | 100 |
| A00000000000001 | 2 | 101 |
| A00000000000001 | 3 | 200 |
| A00000000000002 | 1 | 100 |
| A00000000000002 | 2 | 101 |
| A00000000000003 | 1 | 100 |
| A00000000000003 | 2 | 200 |
| A00000000000004 | 1 | 200 |
| A00000000000004 | 2 | 100 |
| A00000000000005 | 1 | 101 |
| A00000000000005 | 2 | 100 |
+-----------------+--------+---------+
輸出:
+-----------------+--------+---------+---------+
| TransNo | Serial | Project | Flag |
+-----------------+--------+---------+---------+
| A00000000000001 | 1 | 100 | 1 |
| A00000000000001 | 2 | 101 | 1 |
| A00000000000001 | 2 | 200 | 1 |
| A00000000000002 | 1 | 100 | 2 |
| A00000000000002 | 2 | 101 | 2 |
| A00000000000005 | 1 | 101 | 2 |
| A00000000000005 | 2 | 100 | 2 |
| A00000000000003 | 1 | 100 | 3 |
| A00000000000003 | 2 | 200 | 3 |
| A00000000000004 | 1 | 200 | 3 |
| A00000000000004 | 2 | 100 | 3 |
+-----------------+--------+---------+---------+
什麼是'Flag'列邏輯? – Fabio
標誌只是識別具有相同項目集的事務。那些在項目100和101之間承諾的事務被標記爲1,那些100和200被標記爲2.它可以是任何int,char只是一個標識節點。 – Esty