Sql Join Query使用OrderDelivery的总和来获取日期基础上的记录

时间:2015-07-11 09:10:33

标签: sql sql-server

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <form class="form-horizontal" role="form" action="/registrieren" method="post">
        <div class="row">
            <div class="col-xs-6">
                <label for="usr">Surname:</label>
                <input type="text" class="form-control" id="vorname" name="vorname">
            </div>
            <div class="col-xs-6">
                <label for="usr">Name:</label>
                <input type="text" class="form-control" id="name" name="name">
            </div>
        </div>
        <div class="row">
            <div class="col-lg-12">
                <label for="usr">Street:</label>
                <input type="text" class="form-control" id="strasse" name="strasse">
            </div>
        </div>
    </form>
</div>

我编写此查询以获取基于日期SELECT dbo.Customers.Name, dbo.Items.Name AS ItemName, CONVERT(varchar, dbo.OrderDeliveryDetail.CreatedOn, 1) AS [mm/dd/yy], SUM(dbo.OrderDeliveryDetail.DeliveredQuantity) AS DeliveredQuantity FROM dbo.OrderDeliveryDetail INNER JOIN dbo.Customers ON dbo.OrderDeliveryDetail.BusinessUnitId = dbo.Customers.BusinessUnitId INNER JOIN dbo.Items ON dbo.OrderDeliveryDetail.BusinessUnitId = dbo.Items.BusinessUnitId AND dbo.OrderDeliveryDetail.ItemId = dbo.Items.ItemId GROUP BY dbo.Customers.Name, dbo.Items.Name, dbo.OrderDeliveryDetail.CreatedOn 之和的所有记录。但SQL返回了我需要的所有数据,但他没有给我DeliveredQuantity

的总和

1 个答案:

答案 0 :(得分:0)

您需要按日期汇总:

SELECT c.Name, i.Name AS ItemName, 
       CONVERT(varchar(10), od.CreatedOn, 1) AS [mm/dd/yy], 
       SUM(od.DeliveredQuantity) AS DeliveredQuantity
FROM dbo.OrderDeliveryDetail od INNER JOIN
     dbo.Customers c
     ON od.BusinessUnitId = c.BusinessUnitId  INNER JOIN
     dbo.Items i
     ON od.BusinessUnitId = i.BusinessUnitId AND
       od.ItemId = i.ItemId
GROUP BY c.Name, i.Name, CONVERT(varchar(10), od.CreatedOn, 1);
-------------------------^

据推测,CreatedOn也有一个时间组件,这会导致每个日期有多行。

另请注意,由于使用了表别名,查询如何更容易理解。并且,从不在SQL Server中使用varchar()而没有长度。默认长度因上下文而异,您应该明确地防止将来出现错误。