簡體   English   中英

如何設計2組數據之間的交集的SQL查詢

[英]How to design the sql query for intersection between 2 sets of data

我有這些桌子

create table Programs(
Id int identity(1,1) not null,
Days int not null,
Monday bit not null,
Tuesday bit not null,
Wednesday bit not null,
Thursday bit not null,
Friday bit not null,
Saturday bit not null,
Sunday bit not null)

create table ProgramItems(
Id int identity(1,1) not null,
ProgramId int not null,
ItemId int not null
IsActive bit not null)

create table Items(
Id int identity(1,1) not null,
Monday bit not null,
Tuesday bit not null,
Wednesday bit not null,
Thursday bit not null,
Friday bit not null,
Saturday bit not null,
Sunday bit not null)

create table CustomerProgram(
Id int identity(1,1) not null,
CustomerId int not null,
ProgramId int not null,
StartDate datetime not null)

當用戶定義程序時,他應該執行以下步驟1-定義程序日期(星期一,星期二,星期三,星期五),例如2-選擇程序項

我想在網格中顯示與這些天匹配的所有項目

周一,周二,周三,周四可用的項目將顯示在網格中以供選擇,因為計划日與項目日(周一,周二,周三)相同

但是如果項目可用,例如(Thu,Sat)上的項目不應顯示在網格中。

我的問題如何在sql中繼續此查詢?

select * 
from Items
where Id not in(select ItemId from ProgramItems
where ProgramId=1)
/* here i should pick only items that match with the program days*/

提前致謝

至少設置了MondayTuesdayWednesday的以下返回項:

select i.*
from Items i
where Id not in(select ItemId from ProgramItems where ProgramId = 1) and
      (Monday = 1 or Tuesday = 1 or Wednesday = 1);

以下返回設置了全部三天的項目:

select i.*
from Items i
where Id not in(select ItemId from ProgramItems where ProgramId = 1) and
      (Monday = 1 and Tuesday = 1 and Wednesday = 1);

編輯:

如果您有特定的程序,則可以執行以下操作:

select i.*
from Items i join
     Programs p
     on p.id = @ProgramId and
        (i.Monday >= p.Monday and i.Tuesday >= p.Tuesday and i.Wednesday >= p.Wednesday and
         i.Thursday >= p.Thursday and i.Friday >= p.Friday and
         i.Saturday >= p.Saturday and i.Sunday >= p.Sunday
        )
where not exists (select 1
                  from ProgramItems pi
                  where pi.ProgramId = p.id and pi.ItemId = i.Id);

當然這只是一個簡單的連接問題?

Select I.* FROM Items AS I
INNER JOIN ProgramItems AS PI
ON PI.ItemId = I.Id
INNER JOIN Program AS P
ON P.Id = PI.ProgramID
WHERE (I.Monday = 1 OR I.TuesDat = 1 OR I.WednesDay =1) --you get the picture
AND P.Id = 1

但是我必須質疑項目表和程序表中周一至周日位字段的重復:為什么在兩個地方都存在它? 實際上,我將刪除where(I.day = 1等)子句,並根據代碼中所選值是1還是0填充日歷。

試試這個代碼

declare @program int
set @program=1

select * 
from Items i, Programs p
where not exists(select 1 from ProgramItems where p.Id=ProgramId and i.Id=ItemId) and
      ((p.Monday=1 and i.Monday=p.Monday) or
      (p.Tuesday=1 and i.Tuesday=p.Tuesday) or
      (p.Wednesday=1 and i.Wednesday=p.Wednesday) or
      (p.Thursday=1 and i.Thursday=p.Thursday) or
      (p.Friday=1 and i.Friday=p.Friday) or
      (p.Saturday=1 and i.Saturday=p.Saturday) or
      (p.Sunday=1 and i.Sunday=p.Sunday))
where p.Program=@program

這里是一個工作演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM