select
colHeader,
max(case when value = 'value 1' then no else null end) as value1,
max(case when value = 'value 2' then no else null end) as value2,
max(case when value = 'value 1' then price else null end) as value1price,
max(case when value = 'value 2' then price else null end) as value2price
from
your_table
group by colHeader
執行多個步驟查詢帶電作業是希望自我解釋(增加了一些筆記,雖然):
select
*
from
t;
結果:
| COLHEADER | VALUE | NO | PRICE |
|-----------|---------|------|--------|
| Header1 | value 1 | no 1 | price1 |
| Header1 | value 2 | no 2 | price2 |
| Header2 | value 1 | no 3 | price3 |
| Header2 | value 2 | no 4 | price4 |
select
colHeader,
case when value = 'value 1' then no else null end as value1,
case when value = 'value 2' then no else null end as value2,
case when value = 'value 1' then price else null end as value1price,
case when value = 'value 2' then price else null end as value2price
from
t;
結果:
| COLHEADER | VALUE1 | VALUE2 | VALUE1PRICE | VALUE2PRICE |
|-----------|--------|--------|-------------|-------------|
| Header1 | no 1 | (null) | price1 | (null) |
| Header1 | (null) | no 2 | (null) | price2 |
| Header2 | no 3 | (null) | price3 | (null) |
| Header2 | (null) | no 4 | (null) | price4 |
不知道下面的步驟是不是比什麼都更加混亂。它返回列colHeader「摺疊」的行。也就是說,如果沒有使用像max()
那樣的聚合函數,則顯示每個組的隨機行(在這種情況下,每隔第二行被省略)。請注意,這不是標準的SQL,如果我沒有錯誤,只有MySQL允許這樣做。無論如何,這就是爲什麼我們在最後一步使用max()
函數的原因。
select
colHeader,
case when value = 'value 1' then no else null end as value1,
case when value = 'value 2' then no else null end as value2,
case when value = 'value 1' then price else null end as value1price,
case when value = 'value 2' then price else null end as value2price
from
t
group by colHeader;
結果:
| COLHEADER | VALUE1 | VALUE2 | VALUE1PRICE | VALUE2PRICE |
|-----------|--------|--------|-------------|-------------|
| Header1 | no 1 | (null) | price1 | (null) |
| Header2 | no 3 | (null) | price3 | (null) |
最後一步:
select
colHeader,
max(case when value = 'value 1' then no else null end) as value1,
max(case when value = 'value 2' then no else null end) as value2,
max(case when value = 'value 1' then price else null end) as value1price,
max(case when value = 'value 2' then price else null end) as value2price
from
t
group by colHeader;
結果:
| COLHEADER | VALUE1 | VALUE2 | VALUE1PRICE | VALUE2PRICE |
|-----------|--------|--------|-------------|-------------|
| Header1 | no 1 | no 2 | price1 | price2 |
| Header2 | no 3 | no 4 | price3 | price4 |
不知道與查詢,但(這_love line_)CA用PHP完成。 –
@OP你能解釋一下你在輸出中獲得的值是'value 1 no'嗎?它是'價值1'嗎?另外,我可以假設'Header1'可能重複兩次以上? –