如何在SQL Server中水平显示查询中的某些行数据

时间:2018-04-17 18:16:43

标签: sql sql-server

我有这个查询

Dim OWB As Excel.Workbook
Set OWB = GetObject(ActivePresentation.Path & "\Test.xlsx")
OWB.Sheets(1).Copy after:=OWB.Sheets(1)

返回以下结果

select 
    inv.refe, co.color, inv.size, sum(acu.total), bo.wareh 
from 
    inv_article inv 
inner join 
    inv_colors co on inv.color = co.color
inner join 
    inv_store acu on inv.item = acu.item 
inner join 
    inv_bods bo on bo.wareh = acu.wareh
where 
    refers = 'julios' 
    and acu.year = '2018'
group by 
    inv.refe, co.color, inv.size, bo.wareh
having 
    sum(total) != '0'

我希望结果能够横向显示大小 - 就像这样:

JULIOS  BLUE                35      1,00    DENVER      
JULIOS  BLUE                35      1,00    PA
JULIOS  BLUE                36      1,00    FLORIDA    
JULIOS  BLUE                36      2,00    FLORIDA
JULIOS  BLUE                37      2,00    HOUSTON
JULIOS  BLUE                38      2,00    FLORIDA
JULIOS  GREEN               35      1,00    DENVER      
JULIOS  GREEN               35      1,00    PA
JULIOS  GREEN               36      1,00    FLORIDA    
JULIOS  GREEN               36      2,00    FLORIDA
JULIOS  GREEN               37      2,00    HOUSTON
JULIOS  GREEN               38      2,00    FLORIDA

并且总数在每个尺寸的底部

1 个答案:

答案 0 :(得分:0)

你在寻找这样的东西:

 ;WITH cte_base AS(
    SELECT
        inv.refe       AS refe,
        co.color       AS color,
        inv.size       AS SIZE,
        SUM(acu.total) AS 'Values',
        bo.wareh       AS wareh
FROM
        inv_article inv
    INNER JOIN
        inv_colors  co
            ON inv.color = co.color
    INNER JOIN
        inv_store   acu
            ON inv.item = acu.item
    INNER JOIN
        inv_bods    bo
            ON bo.wareh = acu.wareh
WHERE
        refers = 'julios'
        AND acu.year = '2018'
GROUP BY
        inv.refe,
        co.color,
        inv.size,
        bo.wareh
HAVING
        SUM(total) <> '0'
    )
    SELECT refe, color, [35],[36],[37],[38],[39],[40], wareh
    FROM cte_base
    PIVOT (SUM([Values]) 
    FOR size IN ([35],[36],[37],[38],[39],[40])) AS p