2014-09-02 90 views
0

創建主/詳細信息表的摘要視圖我有兩個(簡化)表/班設立這樣的:如何使用SQL

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. 的所有細節由OrderHeader通過OrderHeader wher的TransactionId
  2. 計數作爲列Number of Details
  3. 的細節計數ËQuantityRemaining等於零作爲columnn Completed
  4. 通過OrderHeader命名爲Partially Shipped的細節計數,其中QuantityShipped大於零但小於QuantityOrdered

我試圖查詢兩個OrderHeaderOrderDetails表,並試圖讓子查詢我想要的每一列,但我得到了相同的TransactionId多行。當我使用DISTINCT時,選擇的數字與我所知道的正確的數字不符。

雖然承認這是完全可憐,我能得到一個部分,但準確的結果,只有兩列設置:

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

但我不能把它與其他兩列工作。

回答

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 
+0

謝謝@jonathan快速簡潔的回答。它的工作和你寫的一樣簡單。 – Randy 2014-09-02 20:49:58