在SQL中的不同列中显示多行

时间:2015-12-02 20:26:55

标签: 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
            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

任何建议或任何其他可能的方法来实现这一目标?

1 个答案:

答案 0 :(得分:2)

将当前查询放在子查询中,然后转动子查询

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