我有下表:
UID | Limit |Type
8 | 4 |A
8 | 5 |B
8 | 6 |C
我想要一个查询,它将返回所有这些值,但是在一行中,如下所示:
UID | A | B | C
8 | 4 | 5 | 6
有人知道如何用SQL做到这一点吗?我使用MySQL。
答案 0 :(得分:6)
尝试PIVOT命令。这是一个很好的例子。
http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/
您需要的命令可能如下所示:
SELECT UID, A, B, C
FROM (
SELECT *
FROM table1) t1
PIVOT (SUM(Limit) FOR [Type] IN (A,B,C)) AS pvt
SUM可以被任何其他聚合函数替换
答案 1 :(得分:3)
请说明您正在使用的数据库技术。在SQL Server中,PIVOT是一个不错的选择。在ORACLE中,CONNECT BY语法可能有效。
如果你的类型是固定的,并且不介意一个几乎可以在任何地方工作的丑陋查询,那么下面就足够了:
SELECT
T.UID,
MIN((SELECT Limit FROM TheTable A WHERE A.UID = T.UID AND Type = 'A')) A,
MIN((SELECT Limit FROM TheTable B WHERE B.UID = T.UID AND Type = 'B')) B,
MIN((SELECT Limit FROM TheTable C WHERE C.UID = T.UID AND Type = 'C')) C
FROM TheTable T
GROUP BY T.UID
MIN函数用于避免数据库服务器对GROUP BY子句中不包括A,B和C列的投诉。
邋and而缓慢,但它确实有效。
在大多数数据库系统中可能更快的另一种方法(如果一种类型每个UID有多个记录,请注意这里的笛卡儿):
SELECT
Driver.UID,
A.Limit A,
B.Limit B,
C.Limit C
FROM TheTable Driver
INNER JOIN TheTable A ON Driver.UID = A.UID AND A.Type = 'A'
INNER JOIN TheTable B ON Driver.UID = B.UID AND B.Type = 'B'
INNER JOIN TheTable C ON Driver.UID = C.UID AND C.Type = 'C'
答案 2 :(得分:3)
您可以通过将表连接到自己几次来在MySQL中执行此操作:
select
t1.uid,
t2.limit as A,
t3.limit as B,
t4.limit as C
from
tbl t1
inner join tbl t2 on
t1.uid = t2.uid
and t2.type = 'A'
inner join tbl t3 on
t1.uid = t3.uid
and t3.type = 'B'
inner join tbl t4 on
t1.uid = t4.uid
and t4.type = 'C'
答案 3 :(得分:3)
除了其他建议外,您还可以自行加入表格:
select base.uid, a.limit, b.limit, c.limit
from (select distinct uid from table) base
left join table a on base.uid = a.uid and a.type = 'A'
left join table b on base.uid = b.uid and b.type = 'B'
left join table c on base.uid = c.uid and c.type = 'C'
这假设(uid,type)是行的唯一标识符。