选择并分组 - 计算字段

时间:2015-10-08 21:37:23

标签: sql sql-server

我在SQL Server 2008中完成SQL语句时遇到了一些问题。

我的查询1'如下:

SELECT [Vc_MONTH],
       [Vc_STATE],
       [Vc_PRODUCT],
       SUM ([TOTAL]) as Total_Units,
       SUM ([OPEN]) as Open_Units

FROM [test].[dbo].[Tbl_Summary]

GROUP BY [Vc_MONTH],
         [Vc_REGION],
         [Vc_PRODUCT],

此查询选择月份,地区,产品,总单位总和和未结单位总和。

我已按月,地区和产品分组。 (我有更多的线路)

此查询有效。

我需要的是另一个' query2'按(ALL)表列出的月份,然后选择这两个月的联合。

最后我需要这样的东西

QUERY1

|MONTH | STATE | PRODUCT | TOTAL | OPEN |
|:-----|:------|:--------|:------|:-----|
|JAN   | CA    | PENCIL  | 200   | 160 |
|JAN   | FL    | BOOK    | 300   | 280 |
|FEB   | CA    | PENCIL  | 180   | 150 |
|FEB   | FL    | PENCIL  | 250   | 100 |
|MAR   | CA    | BOOK    | 250   | 100 |
|MAR   | FL    | BOOK    | 100   | 50  |

query2 - 这就是我需要的

|MONTH | STATE | PRODUCT | TOTAL | OPEN |
|:-----|:------|:--------|:------|:-----|
|JAN   | CA    | PENCIL  | 200   | 160 |
|JAN   | FL    | BOOK    | 300   | 280 |
|FEB   | CA    | PENCIL  | 180   | 150 |
|FEB   | FL    | PENCIL  | 250   | 100 |
|MAR   | CA    | BOOK    | 250   | 100 |
|MAR   | FL    | BOOK    | 100   | 50  |

UNION

|ALL   | CA    | PENCIL  | 380   | 310 |
|ALL   | CA    | BOOK    | 250   | 100 |
|ALL   | FL    | PENCIL  | 250   | 100 |
|ALL   | FL    | BOOK    | 400   | 330 |

提前致谢, 路易斯

3 个答案:

答案 0 :(得分:1)

我认为你应该使用union。更简单的查询,没有SELECT (CASE WHEN GROUPING([Vc_MONTH]) = 1 THEN 'ALL' ELSE [Vc_MONTH] END) as [Vc_MONTH], [Vc_STATE], [Vc_PRODUCT], SUM ([TOTAL]) as Total_Units, SUM ([OPEN]) as Open_Units FROM [test].[dbo].[Tbl_Summary] GROUP BY GROUPING SETS (([Vc_MONTH], [Vc_REGION], [Vc_PRODUCT]), ([Vc_REGION], [Vc_PRODUCT]) );

def program_qanda
  # can ask questions on programs
      # TO DO: create this 
      can :cr, ProgramQuestions if can? :read, Programs
      end
      can :read, ProgramAnswers, if can? :read, ProgramQuestions 
      end 
      can :ud, ProgramQuestions.user_question.unanswered
      #can read answer to Q     
end

答案 1 :(得分:0)

不是任何SQL Server Guru,但我认为它有一个with子句:

with monthly as (
  SELECT
    [Vc_MONTH], [Vc_STATE], [Vc_PRODUCT],
    SUM ([TOTAL]) as Total_Units,
    SUM ([OPEN]) as Open_Units
  FROM [test].[dbo].[Tbl_Summary]
  GROUP BY
    [Vc_MONTH], [Vc_STATE], [Vc_PRODUCT]
)
select
  [Vc_MONTH], [Vc_STATE], [Vc_PRODUCT],
  Total_Units, Open_Units
from monthly
union all
select
  '*ALL', [Vc_STATE], [Vc_PRODUCT],
  sum (Total_Units), sum (Open_Units)
from monthly
group by [Vc_STATE], [Vc_PRODUCT]

答案 2 :(得分:0)

所以你已经有了查询1:

SELECT [Vc_MONTH],
   [Vc_STATE],
   [Vc_PRODUCT],
   SUM ([TOTAL]) as Total_Units,
   SUM ([OPEN]) as Open_Units
FROM [test].[dbo].[Tbl_Summary]
GROUP BY [Vc_MONTH],
     [Vc_STATE],
     [Vc_PRODUCT]

接下来你需要GROUP BY Month和Product正确吗?但是,您需要在“Vc_STATE”列中指定一个值,以便两个查询的结果集返回相同的列。

UNION
SELECT [Vc_MONTH],
   'ALL STATES',
   [Vc_PRODUCT],
   SUM ([TOTAL]) as Total_Units,
   SUM ([OPEN]) as Open_Units
FROM [test].[dbo].[Tbl_Summary]
GROUP BY [Vc_MONTH],
     [Vc_PRODUCT]