[英]Join two tables through a pivot table and retrieve specific results in mysql
[英]mysql/pivot table with two tables
我試圖將多行合並為具有不同列的單行,但其給出的方式不同。這是我的數據。
表格1:
| id | name | Invoice value | invoice_date |
|----|------|---------------|--------------|
| 1 | A | 5000 | 30-01-2016 |
| 2 | B | 8000 | 02-05-2016 |
| 3 | C | 10000 | 03-05-2016 |
表2:
| id | invoice_id | duedate | amount | percentage |
|----|------------|------------|--------|------------|
| 1 | 1 | 15-01-2016 | 2500 | 50% |
| 2 | 1 | 30-01-2016 | 2500 | 50% |
| 3 | 2 | 15-02-2016 | 8000 | 100% |
| 4 | 3 | 15-05-2016 | 5000 | 50% |
| 5 | 3 | 19-05-2016 | 2500 | 25% |
| 6 | 3 | 25-05-2016 | 2500 | 25% |
所需的輸出應如下所示
| name | invoice_value | invoice_date | due date1 | due amount1 | due date2 | due amount2 | due date3 | due amount3 |
|------|---------------|--------------|------------|-------------|------------|-------------|------------|-------------|
| A | 5000 | 30-01-2016 | 15-01-2016 | 2500 | 30-01-2016 | 04-11-1906 | null | null |
| B | 8000 | 02-05-2016 | 15-02-2016 | 8000 | null | null | null | null |
| C | 10000 | 03-05-2016 | 15-05-2016 | 5000 | 19-05-2016 | 2500 | 19-05-2016 | 2500 |
這是我的查詢,但是它的給定結果用逗號分隔的duedates.i dnt wnat這樣。
SELECT
T1.name,
T1.invoice_value,
T1.invoice_date,
T1.duedate,
T1.dueamount
FROM
(SELECT
table1.name,
table1.invoice_value,
table1.invoice_date,
GROUP_CONCAT(table2.duedate1) AS duedate,
GROUP_CONCAT(table2.dueamount1) AS dueamount
FROM
table1
LEFT JOIN table2 ON table1.id = table2.invoice_id) T1
GROUP BY T1.id
請一些人幫我整理一下。
在沒有高級知識的情況下,請勿嘗試用一個語句解決此問題。 編寫腳本並將其分為幾個步驟。 如果正確執行,它將運行得非常快(通常比單查詢方法要快)。
步驟可能是:
創建表3(表2),表3中包含來自表1的數據,並按名稱和due_date排序。
通過添加一個列auto_increment和唯一鍵的一部分以及名稱來添加一個列來為每個名稱的出現次數編號:
ALTER TABLE TABLE_3
ADD COLUMN position_id integer auto_increment NOT NULL,
ADD Unique Key positon_number(Name, position_id);
之后,您可以使用position_id來引用第一個,第二個等事件以及相關的Duedate和Dueamount:
select
name, invoice_value, invoice_date, #
if(position_id=1, duedate ,null) as due_date_1,
if(position_id=1, amount ,null) as due_amount_1,
if(position_id=2, duedate ,null) as due_date_2,
if(position_id=2, amount ,null) as due_amount_2,
if(position_id=3, duedate ,null) as due_date_3,
if(position_id=3, amount ,null) as due_amount_3,
if(position_id=4, duedate ,null) as due_date_4,
if(position_id=4, amount ,null) as due_amount_4,
if(position_id=5, duedate ,null) as due_date_5,
if(position_id=5, amount ,null) as due_amount_5
FROM table_3
GROUP BY name;
但是,最好使用客戶ID而不是名稱,因為否則您將需要尋找重復的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.