我试图将多个行放入一个一行中,其中包含根据数据创建的动态列。我有两张带有外键的桌子。
表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 |当我尝试对多列使用group-concat时,它会给出用逗号分隔的结果。但我想要的是期望的输出。请有人帮助解决这个问题,如何编写一个查询。
我使用了以下查询,但它将结果作为逗号分隔的结果:
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发布于 2016-06-06 05:35:47
(从技术上讲,这不是“一个答案”,但声称需要说出来。)
会有任意数量的列,对吗?然后(1)输出是不切实际的,(2)在SQL中生成输出几乎是不可能的。
因此,(1)重新考虑需求,然后(2)考虑是否使用PHP进行操作。
https://dba.stackexchange.com/questions/139908
复制相似问题