简体   繁体   中英

Merging two Schedule rows into one in SQL

Little backstory: We have two scheduling databases that we import from, that feeds Data into our SQL Server. Sometimes that creates duplicate records for the same classroom during the same academic period, but it doesn't happen very often. What I need to do is merge them into one row WITHOUT altering database (as I do not have the rights to do that just yet). I just want it to take effect in the query I am running.

So in the following data you can see that the all of my filtering criteria (AcademicPeriod, BuildingNumber, RoomNumber and DayOfWeek) are all the same but I have two rows that show it is occupied at separate times.

0 = Vacant 1 = Occupied

AcademicPeriod | BuildingNumber | RoomNumber | DayOfWeek | 9:30a | 9:45a | 12:30p | 12:45p

------201401 -------------- 0001 ------------- 00015 ------------- R ---------- 0 ------- 0 -------- 1 --------- 1---

------201401 -------------- 0001 ------------- 00015 ------------- R ---------- 1 ------- 1 -------- 0 --------- 0---

Is there a way to join these two rows within my query (again WITHOUT altering the tables) so that it simply has one row with all '1's in it?

I am on a deadline to figure this out, and I could use any suggestions that you may have.

Thank you!!!

SELECT AcademicPeriod , BuildingNumber , RoomNumber , DayOfWeek
       MAX(930A) AS 930A,
       MAX(945A) AS 945A,
       MAX(1230P) AS 1230P,
       MAX(1245P) AS 1245P

  FROM {YourResultSet} 

 Group BY AcademicPeriod, 
          BuildingNumber, 
          RoomNumber, 
          DayOfWeek

Try this question:

SELECT  x.AcademicPeriod, x.BuildingNumber, x.RoomNumber, x.DayOfWeek,
    MAX(x.[9:30a])  AS [9:30a], 
    MAX(x.[9:45a])  AS [9:45a], 
    MAX(x.[12:30p]) AS [12:30p], 
    MAX(x.[12:45p]) AS [12:45p]
FROM    MySchema.MyTable x
GROUP BY x.AcademicPeriod, x.BuildingNumber, x.RoomNumber, x.DayOfWeek;

select AcademicPeriod, BuildingNumber, RoomNumber, DayOfWeek max(9:30a), max(9:45a), max(12:30p), max(12:45p) from tab group by AcademicPeriod, BuildingNumber, RoomNumber, DayOfWeek

I use constructs like the above, often in an insert into table select... to solve this type of problem.

I don't know how you retrieve your data so my suggestion could be absolutely silly, but what about using a group function and search for the max() value in the occupation columns?

select AcademicPeriod, BuildingNumber, RoomNumber, DayOfWeek, max(9:30a), max(9:45a), max(12:30p), max(12:45p)
from table
group by AcademicPeriod, BuildingNumber, RoomNumber, DayOfWeek

It all depends on how you import your data... could you give further details?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM