[英]How can I display data from the same table side by side
假設我在mysql中有1個表(稱為get),如下所示:
ID S Num
00 1 506
00 2 620
01 1 562
01 2 564
02 1 548
02 2 484
03 1 488
03 2 895
我正在嘗試以以下格式獲取它:
ID S1 S2
00 506 620
01 562 564
02 548 484
03 488 895
到目前為止我有這個,但它給了我一個錯誤:
select id,d.S1,c.S2 from
(select S as S1 from get where S=1)d inner join
(select s as S2 from get where S=2)c using (id);
我仍然不太確定加入,但這似乎有道理。
編輯:S有時只能有1個值,在這些時間內,此值將為S1
您可以使用自聯接,換句話說,您可以在桌面上加入兩次,類似於您的開始方式。 由於您聲明S=1
將始終存在,因此您可以使用以下查詢:
select t1.id,
t1.num S1,
t2.num S2
from yourtable t1
left join yourtable t2
on t1.id = t2.id
and t2.s = 2
where t1.s = 1;
請參閱SQL Fiddle with Demo 。 在表上使用LEFT JOIN將返回值S=1
所有行,即使表中不存在S=2
。
您還可以使用帶有CASE表達式的聚合函數來獲取結果:
select
id,
sum(case when s = 1 then num end) S1,
sum(case when s = 2 then num end) S2
from yourtable
group by id;
盡管JOIN可能不是解決問題的最佳方法,但是您可以通過以下方式獲得所需的結果
SELECT t1.id, t.Num [S1], t2.Num [S2]
FROM Table t1
LEFT JOIN Table t2 ON t1.id = t2.id AND t1.s <> t2.s
如果表的S列中可能還有其他值,也請參考PIVOT 。
編輯:在看到可能有沒有S = 2的id的評論后,將INNER JOIN
更改為LEFT JOIN
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.