我有两个(简化的)表/类设置如下:
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; }
}
我正在尝试创建一个返回的视图:
TransactionId
OrderHeader
列Number of Details
OrderHeader
的详细信息,其中QuantityRemaining
等于零为Completed
OrderHeader
名为Partially Shipped
的详细信息,其中QuantityShipped
大于零但小于QuantityOrdered
我已经尝试查询OrderHeader
和OrderDetails
表,并尝试为我想要的每个列进行子查询,但我最终获得了多行TransactionId
。当我使用DISTINCT
选择时,数字与我所知的正确无关。
虽然承认这完全是可怜的,但我只能用两列来获得部分但准确的结果集:
SELECT
TransactionId,
COUNT(*) AS [Number of Details]
FROM OrderDetails
GROUP BY TransactionID
但我无法使用其他两个专栏。
答案 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