如果有人知道更好的標題,請繼續並改變它。簡單,純粹的Sql查詢(擺脫重複結果)
我知道我的嘗試是最好的mediacore,所以如果你知道一個更好的aproach請分享。我會盡量保持簡單明瞭:
我的數據庫表:
ID | Category | Number | NumberInCategory |
1 A 31 101
2 B 31 107
3 C 31 121
4 A 32 191
5 A 33 165
6 B 32 156
7 C 32 127
我需要什麼樣的輸出:
Number | A | B | C
31 101 107 121
32 191 156 127
33 165 NULL NULL
我嘗試:
SELECT (SELECT DISTINCT(Number) FROM MYDB V WHERE F.ID = V.ID) AS Id,
(SELECT NumberInCategory FROM MYDB V WHERE F.Number = V.Number AND Category = 'A') AS CategoryA ,
(SELECT NumberInCategory FROM MYDB V WHERE F.Number = V.Number AND Category = 'B') AS CategoryB,
(SELECT NumberInCategory FROM MYDB V WHERE F.Number = V.Number AND Category = 'C') AS CategoryC
FROM MYDB F;
我的結果:
31|101|107|121
31|101|107|121
31|101|107|121
32|191|156|127
33|165||
32|191|156|127
32|191|156|127
我只是不能找到一種方法來得到這個工作。
我有人想幫助這裏充滿了腳本https://www.tutorialspoint.com/execute_sql_online.php
BEGIN TRANSACTION;
/* Create a table called SAMPLE */
CREATE TABLE MYDB(Id integer PRIMARY KEY, Category text, Number integer, NumberInCategory integer);
/* Create few records in this table */
INSERT INTO MYDB VALUES(1,'A',31,101);
INSERT INTO MYDB VALUES(2,'B',31,107);
INSERT INTO MYDB VALUES(3,'C',31,121);
INSERT INTO MYDB VALUES(4,'A',32,191);
INSERT INTO MYDB VALUES(5,'A',33,165);
INSERT INTO MYDB VALUES(6,'B',32,156);
INSERT INTO MYDB VALUES(7,'C',32,127);
COMMIT;
/* Display all the records from the table */
SELECT * FROM MYDB;
SELECT (SELECT DISTINCT(Number) FROM MYDB V WHERE F.ID = V.ID) AS Id,
(SELECT NumberInCategory FROM MYDB V WHERE F.Number = V.Number AND Category = 'A') AS CategoryA ,
(SELECT NumberInCategory FROM MYDB V WHERE F.Number = V.Number AND Category = 'B') AS CategoryB,
(SELECT NumberInCategory FROM MYDB V WHERE F.Number = V.Number AND Category = 'C') AS CategoryC
FROM MYDB F;
編輯 簡單GROUP BY在年底做這項工作.____。
SELECT (SELECT Number FROM MYDB V WHERE F.ID = V.ID) AS Id,
(SELECT NumberInCategory FROM MYDB V WHERE F.Number = V.Number AND Category = 'A') AS CategoryA ,
(SELECT NumberInCategory FROM MYDB V WHERE F.Number = V.Number AND Category = 'B') AS CategoryB,
(SELECT NumberInCategory FROM MYDB V WHERE F.Number = V.Number AND Category = 'C') AS CategoryC
FROM MYDB F
GROUP BY NUMBER;
結果:
31|101|107|121
32|191|156|127
33|165||
雖然從接受的答案的形式給出(由@Gordon Linoff)是更好的。
嘗試以下問題的答案來自Sagi:https://stackoverflow.com/questions/45920094/sql-server-trying-to-de-normalize-my-table/45920185?noredirect=1#評論78800061_45920185 – Eli
你確定只有三個類別,或者可以有任何數量的? – Greenspark
@Greenspark在這種情況下,我有限的金額(只有那3) – cantdoanything33