我想要在整个月份和全年都没有订单的产品列表。
这是我的查询:
SELECT DISTINCT(p.ProductName),
DATEPART(MM,o.OrderDate),DATEPART(YY,o.OrderDate)
FROM Products p
JOIN [Order Details] od on p.ProductID = od.ProductID
JOIN Orders o on o.OrderID = od.OrderID
GROUP BY (p.ProductName), DATEPART(MM,o.OrderDate),DATEPART(YY,o.OrderDate)
答案 0 :(得分:2)
使用define: in definition of dotproduct, found bad argument a
-- an error. To debug this try: debugmode(true);
:
not exists
select p.*
from products p
where not exists (select 1
from Orders o join
[Order Details] od
on o.OrderID = od.OrderID
where p.ProductID = od.ProductID and
year(o.orderdate) = ?
);
用于利息年度。
答案 1 :(得分:0)
我在下面的代码中使用类来模拟您的数据库。看看此代码是否有效
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Product> Products = new List<Product>();
List<Order> Orders = new List<Order>();
var results = (from o in Orders
join p in Products on o.ProductID equals p.ProductID
select new {order = o, name = p.ProductName})
.OrderByDescending(x => x.order.OrderDate)
.GroupBy(x => x.order.ProductID)
.Select(x => x.FirstOrDefault()) //get last order for each product
.Where(x => x.order.OrderDate < DateTime.Now.AddMonths(-6))
.Select(x => new { Name = x.name, ID = x.order.ProductID, Date = x.order.OrderDate})
.ToList();
}
}
public class Product
{
public string ProductName { get; set; }
public string ProductID { get; set; }
}
public class Order
{
public DateTime OrderDate { get; set; }
public string ProductID { get; set; }
}
}
此代码效率更高,因为它不必加入不需要的项目
var results = Orders.OrderByDescending(x => x.OrderDate)
.GroupBy(x => x.ProductID)
.Select(x => x.FirstOrDefault()) //get last order for each product
.Where(x => x.OrderDate < DateTime.Now.AddMonths(-6))
.Select(x => new { Name = Products.Where(y => y.ProductID == x.ProductID).FirstOrDefault().ProductName , ID = x.ProductID, Date = x.OrderDate })
.ToList();
如果没有用于产品的订单
var resultsx = (from o in Orders
join p in Products on o.ProductID equals p.ProductID into ps
from p in ps.DefaultIfEmpty()
select new { order = o, name = p.ProductName })
.OrderByDescending(x => x.order == null ? new DateTime() : x.order.OrderDate)
.GroupBy(x => x.order.ProductID)
.Select(x => x.FirstOrDefault()) //get last order for each product
.Where(x => x.order == null ? true : x.order.OrderDate < DateTime.Now.AddMonths(-6))
.Select(x => new { Name = x.name, ID = x.order == null ? "" : x.order.ProductID, Date = x.order == null ? new DateTime() : x.order.OrderDate })
.ToList();