SQL Server按列到行查询结果

时间:2018-06-07 03:37:32

标签: sql sql-server

这是我的示例代码:

SQL Fiddle

我需要这样的结果:

category    outlet1     outlet2     outlet3
Sale        70          20          40
Expense     250         130         200

我该怎么做?

编辑:我的网点没有修好,对不起事先告诉我们。

3 个答案:

答案 0 :(得分:1)

您可以solve your particular problem使用条件聚合:

SELECT c.category,
       SUM(CASE WHEN o.outletname = 'Outlet1' THEN t.amt ELSE 0 END) as Outlet1,
       SUM(CASE WHEN o.outletname = 'Outlet2' THEN t.amt ELSE 0 END) as Outlet2,
       SUM(CASE WHEN o.outletname = 'Outlet3' THEN t.amt ELSE 0 END) as Outlet3
FROM tblcategory c INNER JOIN
     tbltran t
     ON t.catid = c.id INNER JOIN
     tbloutlet o
     ON o.id = t.outletid
GROUP BY c.category;

如果未修复插座名称,则需要动态SQL。使用单个SELECT查询无法解决问题。

答案 1 :(得分:1)

这里有动态奥特莱斯http://sqlfiddle.com/#!18/a7b09/25

test_methods <- list(
  Mean08 = function(x) meanf(x, h = 8),
  Mean10 = function(x) meanf(x, h = 10),
  RW8 = function(x) rwf(x, h = 8,
  RWdrift8 = function(x, ...) rwf(x, h = 8, drift = TRUE, ...)
)

答案 2 :(得分:0)

您也可以使用PIVOT运算符

SELECT *
FROM
(
    SELECT category, outletname, amt
    FROM   tblcategory c
    INNER JOIN tbltran t ON t.catid = c.id
    INNER JOIN tbloutlet o ON o.id = t.outletid
) d
PIVOT
(
     SUM(amt)
     FOR outletname in ([Outlet1] , [Outlet2] , [Outlet3])
) p

编辑:下面是动态SQL版本

declare @Outlets nvarchar(max),
    @SQL    nvarchar(max)

select  @Outlets = isnull(@Outlets + ',', '') + quotename(outlet)
from    outlet

select  @SQL = '
SELECT *
FROM
(
    SELECT category, outletname, amt
    FROM   tblcategory c
    INNER JOIN tbltran t ON t.catid = c.id
    INNER JOIN tbloutlet o ON o.id = t.outletid
) d
PIVOT
(
     SUM(amt)
     FOR outletname in (' + @Outlets + ')
) p'

print   @SQL  -- print out for verification
exec    sp_executesql @SQL