在SQL中将多行显示为不同的列
我有以下查询,显示同一产品但不同销售状态的不同行中的产品列表:在SQL中将多行显示为不同的列,sql,sql-server,pivot,Sql,Sql Server,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
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
现在我需要将输出显示为:
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
Total Items
是一个列名。它不应该有空间分隔。用户“项目总数”
instead@vkp你的意思是应该在单引号“
?@Juan.字符串的单引号之间。这是一个列。我尝试了单引号或双引号,但仍然会出现错误“关键字“PIVOT”附近的语法不正确”。它需要放在方括号中……或者更好的是,从派生列名中去掉空格。列名中的空格只会给代码增加不必要的复杂性。