使用SQL在内部联接表中汇总2列

时间:2016-01-30 14:47:57

标签: sql

我认为对于那些知道一点SQL的人来说,这应该相对容易。

这是我目前的剧本:

SELECT t1.Invoice_Number
      ,t1.Override_Cashier_ID
      ,t1.Exception_Type
      ,t1.ItemNum
      ,t1.Amount
      ,t1.Quantity
      ,t1.Amount*t1.Quantity AS Total
      ,t1.Reason_Code
      ,t2.DateTime
  FROM [esql].[dbo].[Invoice_Exceptions] AS t1
  INNER JOIN [esql].[dbo].[Invoice_Totals] AS t2
  ON  t1.Invoice_Number = t2.Invoice_Number
  WHERE t1.Exception_Type = 2
  AND CAST(t2.DateTime as date) > '20160127'
  AND CAST(t2.DateTime as date) < '20170101'

我想完成两件事:

  1. 总结&#39; Total&#39;列,例如:sum(t1.Amount * t1.Quantity)AS Total
  2. 按&#39; Reason_Code&#39;分组这是一个字符串。让我们说原因代码包含两种不同的价值可能性,&#34; me&#34;和&#34;你&#34;。我想在查询运行后只显示2行,每个原因代码包含总和值1。
  3. 一些示例数据将是:

    “数量”和“数量”列均为小数。我希望最终数据看起来像:

    Reason_Code  -  Total  -  Date_Range
    Me              4000      2016-01-27 - 2017-01-01
    You             3500      2016-01-27 - 2017-01-01
    
    
    Where some sample data may be:
    
    Invoice_Number  -  Reason_Code  -  Amount  -  Quantity  -  Total  -  DateTime
    12345              Me              500        2            1000      2016-01-29 21:24:07.000
    12346              Me              1000       3            3000      2016-01-29 23:15:19.000
    12347              You             500        1            500       2016-01-29 19:00:17.000
    12348              You             1000       3            3000      2016-01-29 21:46:29.000
    

    我希望这很简洁!谢谢你的帮助!

    编辑:

    因此,到目前为止使用的建议,我意识到我有太多的数据带来了SQL不知道该怎么做。我现在有这个,95%在那里:

    SELECT
        sum(t1.Amount*t1.Quantity) AS Total
        ,t1.Reason_Code
    
        FROM [esql].[dbo].[Invoice_Exceptions] AS t1
        INNER JOIN [esql].[dbo].[Invoice_Totals] AS t2
    
        ON  t1.Invoice_Number = t2.Invoice_Number
    
        WHERE t1.Exception_Type = 2
        AND CAST(t2.DateTime as date) > '20160127'
        AND CAST(t2.DateTime as date) < '20170101'
    
        GROUP BY t1.Reason_Code
    

    现在以任何方式显示日期范围?

1 个答案:

答案 0 :(得分:0)

听起来你可以做你所建议的: 添加GROUP BY Reason_Code子句并在sum(t1.Amount*t1.Quantity) AS Total语句中使用SELECT。但是你需要定义如何处理你想要包含在你的两行中的其他列。要么必须将它们添加到GROUP BY,要么必须找到合适的聚合函数来确定要包含的值。