您没有指定您正在使用的 RDBMS。但这基本上是一个PIVOT
.
MySQL:
如果您使用的是 MySQL,它没有PIVOT
函数,但可以使用CASE
语句和聚合函数进行复制。有两种方法可以做到这一点 - 使用硬编码值的静态版本或使用准备好的语句的动态版本。
静态版本 MySQL(参见SQL fiddle with demo):
select m.typeID,
sum(case when t.typename = 'type 1' then m.quantity else 0 end) Type1,
sum(case when t.typename = 'type 2' then m.quantity else 0 end) Type2,
sum(case when t.typename = 'type 3' then m.quantity else 0 end) Type3
from invTypeMaterials m
inner join invTypes t
on m.typeID = t.typeID
group by m.TypeId;
动态版本 MySQL(参见SQL Fiddle with Demo):
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'sum(case when t.typename = ''',
t.typename,
''' then m.quantity else 0 end) ',
replace(t.typename, ' ', '')
)
) INTO @sql
from invTypeMaterials m
inner join invTypes t
on m.typeID = t.typeID;
SET @sql = CONCAT('SELECT m.typeID, ', @sql, '
from invTypeMaterials m
inner join invTypes t
on m.typeID = t.typeID
GROUP BY m.TypeId');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SQL Server 有一个PIVOT
函数,您可以静态或动态地执行此操作。
静态版本 SQL Server(参见SQL Fiddle with Demo):
select typeid,
isnull([Type 1], 0) type1,
isnull([Type 2], 0) type2,
isnull([Type 3], 0) type3
from
(
select m.TypeId,
m.quantity,
t.typename
from invTypeMaterials m
inner join invTypes t
on m.typeID = t.typeID
) x
pivot
(
sum(quantity)
for typename in ([Type 1], [Type 2], [Type 3])
) p
动态版本 SQL Server(参见SQL Fiddle with Demo):
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX),
@colsNull as nvarchar(max)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(typename)
from invTypes
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsNull
= STUFF((SELECT distinct ', IsNull(' + QUOTENAME(typename) + ', 0) as '+ replace(typename, ' ', '')
from invTypes
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT typeid, ' + @colsNull + ' from
(
select m.TypeId,
m.quantity,
t.typename
from invTypeMaterials m
inner join invTypes t
on m.typeID = t.typeID
) x
pivot
(
sum(quantity)
for typename in (' + @cols + ')
) p '
execute(@query)