如何使用SQL创建主/明细表的摘要视图

时间:2014-09-02 20:07:17

标签: sql sql-server sql-server-2008-r2

我有两个(简化的)表/类设置如下:

public class OrderHeader
{
    public OrderHeader()
    {
        Details = new HashSet<OrderDetail>();
    }

    [Key]
    public int TransactionId { get; set; }
    public string CustomerName { get; set; }
    public virtual ICollection<OrderDetail> Details { get; set; }
}

public class OrderDetail
{
    [Key]
    public int DetailId { get; set; }
    public int ItemId { get; set; }
    public int QuantityOrdered { get; set; }
    public int QuantityShipped { get; set; }
    public int QuantityRemaining { get; set; }
    public int TransactionId { get; set; }

    [ForeignKey("TransactionId")]
    public virtual OrderHeader Header { get; set; }
}

我正在尝试创建一个返回的视图:

  1. TransactionId
  2. OrderHeaderNumber of Details
  3. 计算所有详细信息
  4. OrderHeader的详细信息,其中QuantityRemaining等于零为Completed
  5. OrderHeader名为Partially Shipped的详细信息,其中QuantityShipped大于零但小于QuantityOrdered
  6. 我已经尝试查询OrderHeaderOrderDetails表,并尝试为我想要的每个列进行子查询,但我最终获得了多行TransactionId。当我使用DISTINCT选择时,数字与我所知的正确无关。

    虽然承认这完全是可怜的,但我只能用两列来获得部分但准确的结果集:

        SELECT
            TransactionId,
            COUNT(*) AS [Number of Details]
        FROM OrderDetails
        GROUP BY TransactionID
    

    但我无法使用其他两个专栏。

1 个答案:

答案 0 :(得分:1)

这样的东西?

SELECT
  TransactionId,
  COUNT(*) AS [Number of Details],
  Sum(CASE WHEN QuantityRemaining = 0 THEN 1 ELSE 0 END) AS [Completed],
  Sum(CASE WHEN QuantityShipped > 0 AND QuantityShipped < QuantityOrdered THEN 1 ELSE 0 END) AS [Partially Shipped]
FROM OrderDetails
GROUP BY TransactionID