4

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

主表:

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

4 回答 4

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
于 2012-08-05T20:06:25.060 回答
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

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

在此处输入图像描述

于 2012-08-05T20:27:56.053 回答
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
;
于 2013-01-28T07:08:53.620 回答
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;

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

于 2012-08-05T20:26:32.333 回答