我正在尝试做一些简单的事情,但未能在SQL中应用。基本上,我有两个表 - 一个叫做CarHires,它只包含三列 - CarID,StartDate(当租车时)和EndDate(当车返回时)。和日期维度 - DimDate。
我想要实现的是计算每天租用的汽车数量。
这是SQL Fiddle我嘲笑让事情变得简单。
答案应该如下:
public partial class MyDBContext : IdentityDbContext<ApplicationUser>
{
public FunkaDbContext()
: base("name=MyDBContext", throwIfV1Schema: false)
{
Database.SetInitializer<MyDBContext>(new DropCreateDatabaseIfModelChanges<MyDBContext>());
}
public virtual DbSet<educationSignup> EducationSignups { get; set; }
public virtual DbSet<ParticipantsInformation> ParticipantsInformations { get; set; }
public virtual DbSet<PaymentInformation> PaymentInformations { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<educationSignup>()
.HasMany(e => e.participantsInformations)
.WithRequired(e => e.educationSignup)
.HasForeignKey(e => e.SignupId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<educationSignup>()
.HasMany(e => e.paymentInformations)
.WithRequired(e => e.educationSignup)
.HasForeignKey(e => e.SignupId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<IdentityUser>().HasKey<string>(u => u.Id);
modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
}
public static MyDbContext Create()
{
return new MyDbContext();
}
}
非常感谢任何帮助!
答案 0 :(得分:1)
这有效:
SELECT D.Fulldate,
ISNULL(COUNT(*),0) AS NumberofCars
FROM DimDate D
LEFT JOIN CarHires C
ON D.Fulldate BETWEEN C.Startdate AND C.Enddate
GROUP BY D.Fulldate
ORDER BY D.Fulldate;
答案 1 :(得分:0)
您根据startDate
错误地加入了DimDate和CarHires,不需要full inner join
:
select dimdate.Fulldate,
COUNT(CarID) AS NumberofCars
FROM DimDate, CarHires
WHERE dimdate.Fulldate BETWEEN CarHires.Startdate AND CarHires.Enddate
GROUP BY dimdate.Fulldate