對於HANA查詢應該是這樣的(用一些測試數據):
create column table "CustomerItems"
("CustomerID" nvarchar(10),
"Items" nvarchar(10),
"CRank" integer
);
insert into "CustomerItems" ("CustomerID", "Items", "CRank") values ('1', '1', 1);
insert into "CustomerItems" ("CustomerID", "Items", "CRank") values ('1', '1', 1);
insert into "CustomerItems" ("CustomerID", "Items", "CRank") values ('1', '2', 4);
insert into "CustomerItems" ("CustomerID", "Items", "CRank") values ('1', '2', 4);
insert into "CustomerItems" ("CustomerID", "Items", "CRank") values ('2', '1', 3);
insert into "CustomerItems" ("CustomerID", "Items", "CRank") values ('2', '1', 3);
insert into "CustomerItems" ("CustomerID", "Items", "CRank") values ('2', '3', 5);
select "CustomerID", Sum(distinct("CRank"))
from "CustomerItems"
group by "CustomerID"
order by "CustomerID"
我不會用「等級」作爲列名。這是一個reserved word(窗口函數),可能會導致混淆。
對於MySQL,只需將create column table
替換爲create table
,並用反引號替換雙引號。
如果這回答你的問題,我還會推薦一些關於SQL的入門書籍或在線教程。 如果沒有,請提供更多的信息,創建表語句等
編輯後的評論和更改測試數據:
如果要總結一下您的客戶/產品的不同組合的「行列」,試試這個一個(對MySQL再次反引號,而不是雙引號,你必須給子查詢自己的別名):
select "CustomerID", sum("CRank")
from
(
select distinct "CustomerID", "Items", "CRank"
from "CustomerItems"
)
group by "CustomerID"
order by "CustomerID"
嗨克里斯托弗,感謝您的回答。你已經回答了這個問題,但是這並不能滿足什麼時候有一個額外的項目與其他項目相同。 「我已經更新了問題中的表格。」我會明確地考慮你通過一本介紹性書籍的建議。 – Sai