SQL:如何根据同一个表中的其他列值创建新列

时间:2012-08-05 19:59:31

标签: sql sql-server-2008 tsql pivot

我有两张桌子,主要和单位。

主表:

Todate   Unit   CategoryID   Quantity
1/7/2012  1        S            300
1/7/2012  1        U            350
2/7/2012  2        S            220
3/7/2012  2        S             50
3/7/2012  2        U            330
4/7/2012  1        S            200
4/7/2012  1        U            180

S =销售,U =升级

单位表:

UnitNum   UnitName
1         Measures
2         Performance

我需要得到这个结果:

Todate   UnitNum   UnitName    Sales    Upgrades
1/7/2012    1      Measures     300       350
2/7/2012    2      Performance  220
3/7/2012    2      Performance   50       330
4/7/2012    1      Measures     200       180

意思是我需要创建2列 - 销售和升级,具体取决于CategoryID中的值,我需要它们在同一行。 到目前为止我所拥有的是

select Todate, Main.Unit, UnitName,
case when CategoryID = 'S' then Quantity end as Sales,
case when CategoryID = 'U' then Quantity end as Upgrades
from Main join Units on Main.UnitNum = Units.UnitNum
group by  Todate, Main.Unit, UnitName

它为我提供了2个新列,但它们位于两个单独的行中。

我真的很感激有任何帮助解决这个问题! 谢谢

4 个答案:

答案 0 :(得分:1)

您只需要围绕case语句进行汇总查询。

select m.todate
     , m.unit
     , u.unitname
     , sum(case when m.categoryid = 'S' then quantity end ) as sales
     , sum(case when m.categoryid = 'U' then quantity end ) as upgrages
  from main m
  join units u
    on m.unit = u.unitnum
 group by m.todate, m.unit, u.unitname

答案 1 :(得分:1)

你需要这样的东西:

SELECT
    Todate, m.Unit, UnitName,
    Sales = (SELECT SUM(Quantity)
             FROM dbo.Main m2 
             WHERE m.Todate = m2.Todate AND CategoryID = 'S'),
    Updates = (SELECT SUM(Quantity)
               FROM dbo.Main m2 
               WHERE m.Todate = m2.Todate AND CategoryID = 'U')
FROM
    dbo.Main m 
INNER join 
    dbo.Units u on m.Unit = u.UnitNum
GROUP BY  
    Todate, m.Unit, UnitName
ORDER BY  
    Todate, m.Unit, UnitName

这似乎正在返回您正在寻找的输出:

enter image description here

答案 2 :(得分:0)

您需要自己连接主表:

 SELECT m1.todate, m1.unit AS unitnum, u.unitname,
        SUM(m1.quantity) AS sales, SUM(m2.quantity) AS upgrades
   FROM (SELECT todate, unit, quantity FROM Main WHERE category = 'S') AS m1
   FULL OUTER JOIN
        (SELECT todate, unit, quantity FROM Main WHERE category = 'U') AS m2
     ON m1.todate = m2.todate AND m1.unit = m2.unit
   JOIN units AS u
     ON m1.unit = u.unitnum
  GROUP BY m1.todate, m1.unit, u.unitname
  ORDER BY m1.todate, m1.unit, u.unitname;

还有许多其他编写相同查询的等效方法;不过,这个问题可以很好地保持问题的对称性。 (已更新以在m1m2子查询之间使用FULL OUTER JOIN,以处理销售没有升级或没有销售升级的情况。

答案 3 :(得分:0)

您也可以使用PIVOT

WITH data AS (
  SELECT
    m.Todate,
    m.UnitNum,
    u.UnitName,
    Category = CASE m.CategoryID
                 WHEN 'S' THEN 'Sales'
                 WHEN 'U' THEN 'Upgrades'
               END,
    Quantity
  FROM Main m
  INNER JOIN Units u
  ON m.UnitNum = u.UnitNum
)
SELECT
  Todate,
  UnitNum,
  UnitName,
  Sales,
  Upgrades
FROM data
PIVOT (
  SUM(Quantity) FOR Category IN (Sales, Upgrades)
) p
;