在 SQL 中将多行显示到不同的列中
Show multiple rows into different columns in SQL
我有以下查询,它显示了同一产品但不同销售状态的不同行中的产品列表:
select distinct productname as 'Product', sale_status as 'Sold/Unsold', count(distinct i.item_number) as 'Total Items'
from item i
left join department d on i.item_number = d.item_number
where d.term = 'WINTER' and d.year = '2014'
group by productname,sale_status
order by productname
输出为:
Product Sold/Unsold Total Items
Bags SOLD 20
Bags UNSOLD 100
Shoes SOLD 30
Shoes UNSOLD 50
现在我需要将输出显示为:
Product SOLD UNSOLD Total Items
Bags 20 100 120
Shoes 30 50 80
我尝试使用 PIVOT 来实现如下所示的任务,但我无法实现这个目标。它说:关键字 'PIVOT'.
附近的语法不正确
select distinct productname as 'Product', sale_status as 'Sold/Unsold', count(distinct i.item_number) as 'Total Items'
from item i
left join department d on i.item_number = d.item_number
where d.term = 'WINTER' and d.year = '2014'
group by productname,sale_status
order by productname
PIVOT
(
SUM (Total Items)
FOR [Sold/Unsold] IN ([SOLD], [UNSOLD])
) as P
有什么建议或任何其他可能的方法来实现这个目标吗?
将您当前的查询放在子查询中,然后旋转您的子查询
SELECT Product,
[SOLD],
[UNSOLD],
[SOLD] + [UNSOLD] AS [Total Items]
FROM
(
SELECT DISTINCT
productname AS [Product],
sale_status AS [Sold/Unsold],
COUNT(DISTINCT i.item_number) AS [Total Items]
FROM
item i
LEFT JOIN department d ON i.item_number = d.item_number
WHERE
d.term = 'WINTER'
AND d.year = '2014'
GROUP BY
productname,
sale_status
) T
PIVOT
(
SUM([Total Items])
FOR [Sold/Unsold] IN ([SOLD],[UNSOLD])
) p
我有以下查询,它显示了同一产品但不同销售状态的不同行中的产品列表:
select distinct productname as 'Product', sale_status as 'Sold/Unsold', count(distinct i.item_number) as 'Total Items'
from item i
left join department d on i.item_number = d.item_number
where d.term = 'WINTER' and d.year = '2014'
group by productname,sale_status
order by productname
输出为:
Product Sold/Unsold Total Items
Bags SOLD 20
Bags UNSOLD 100
Shoes SOLD 30
Shoes UNSOLD 50
现在我需要将输出显示为:
Product SOLD UNSOLD Total Items
Bags 20 100 120
Shoes 30 50 80
我尝试使用 PIVOT 来实现如下所示的任务,但我无法实现这个目标。它说:关键字 'PIVOT'.
附近的语法不正确select distinct productname as 'Product', sale_status as 'Sold/Unsold', count(distinct i.item_number) as 'Total Items'
from item i
left join department d on i.item_number = d.item_number
where d.term = 'WINTER' and d.year = '2014'
group by productname,sale_status
order by productname
PIVOT
(
SUM (Total Items)
FOR [Sold/Unsold] IN ([SOLD], [UNSOLD])
) as P
有什么建议或任何其他可能的方法来实现这个目标吗?
将您当前的查询放在子查询中,然后旋转您的子查询
SELECT Product,
[SOLD],
[UNSOLD],
[SOLD] + [UNSOLD] AS [Total Items]
FROM
(
SELECT DISTINCT
productname AS [Product],
sale_status AS [Sold/Unsold],
COUNT(DISTINCT i.item_number) AS [Total Items]
FROM
item i
LEFT JOIN department d ON i.item_number = d.item_number
WHERE
d.term = 'WINTER'
AND d.year = '2014'
GROUP BY
productname,
sale_status
) T
PIVOT
(
SUM([Total Items])
FOR [Sold/Unsold] IN ([SOLD],[UNSOLD])
) p