我怎样才能在同一张桌子上查询&获得2列

时间:2017-10-23 06:06:51

标签: sql-server-2012 ssms

我的这张表包含以下数据

+-------+-----------+-------+-------+
| Owner | closeDate | stage | value |  
+-------+-----------+-------+-------+
| Abc   | 1-1-2017  | won   |  1000 |  
| Abc   | 31-1-2017 | won   |  2000 |  
| Abc   | 3-1-2017  | lost  |  1000 |  
| Abc   |  1-2-2017 | won   |  5000 |  
| Def   | 1-2-2017  | won   |  3000 |  
| Def   | 28-2-2017 | won   |  4000 |  
+-------+-----------+-------+-------+

我的目标是这样的结果,它将每个所有者每月的总价值分组为仅获胜的阶段

+-------+----------+----------+
| Owner | JanValue | FebValue |  
+-------+----------+----------+
| Abc   |     3000 |     5000 |  
| Def   |        0 |     7000 |  
+-------+----------+----------+

我已经尝试过此查询,但结果是记录

  SELECT Owner, sum(value) ,datename(month, closedate) as 'month'
  FROM Table1
   where closedate between '2017/01/1' and '2017/01/31' and stage='won'
GROUP BY Owner,datename(month, closedate)

UNION ALL


  SELECT Owner, sum(value) ,datename(month, closedate) as 'month'
  FROM Table1
   where closedate between '2017/02/1' and '2017/02/28' and stage='won'
GROUP BY Owner,datename(month, closedate)

2 个答案:

答案 0 :(得分:1)

您正在寻找一个数据透视查询,这次涉及截止日期的月份:

SELECT
    Owner,
    SUM(CASE WHEN DATEPART(month, closeDate) = 1 THEN value END) AS JanValue,
    SUM(CASE WHEN DATEPART(month, closeDate) = 2 THEN value END) AS FebValue,
    ...
FROM Table1
WHERE
    stage = 'won' AND
    DATEPART(year, closeDate) = 2017
GROUP BY
    Owner;

请注意,当您想要考虑多年的月度报告时,这种方法会变得有点紧张。在这种情况下,您可能希望使用动态SQL来执行数据透视。但是,在这种情况下,在列之间有这么多个月并不是最易读的输出IMO。

答案 1 :(得分:0)

尝试使用动态结果

SELECT
  *
  FROM
  (
      SELECT
        *
        FROM
        (
          SELECT
            Owner,
            CloseDate = DATENAME(month,CAST(CloseDate AS DATE)),
            Val
            FROM Table1
        )T
        PIVOT
        (
          SUM(VAL)
          FOR CloseDate IN
          (
            [January],[February],[March],[April],[May],[June],[July],[August],[September],[October],[November],[December]
          )
        )Pvt
  )Q

这将是您的样本结果

Sample Result

以下输入

Sampel Input

结果是而不过滤舞台。您可以通过以下选择

给出它
SELECT
            Owner,
            CloseDate = DATENAME(month,CAST(CloseDate AS DATE)),
            Val
            FROM Table1
where <Your Conditions>