I want to calculate how many drivers have drove too fast. I have a table traffic. In this table on each row I can see how many cars drove in different speed categories. For this issue I only need the colums amount_drivers1 until amount_drivers10.
I have ten different speed categories (for example the values of speed_categorie colums 1-10 are: 20,30,40,50,60,70,80,90,100,110) in the table speedcategories These are different per way. For each row I have to find the speed categories per way. Speed_categorie1 is related to amount_drivers1, speed_categorie2 is related to amount_drivers2...
Then I have to use the column max_speed from the table MAX_SPEED. I have to loop trough every speed_categorie column to see if the speed_categorie is above the max_speed column. If not do nothing, if yes the amount of cars from the traffic table (the value of the column amount_drivers) has to taken into the column 'to_hard'.
The relation between the max_speed, speed_categories and traffic tables is the column 'way'. This is the foreign key.
For example the max_speed=60 (from the max_speed_table). Then only the the speed categories 70,80,90,100 and 110 (from speed_categorie table) are eligible. Then the amount of drivers from the amount_drivers6, amount_drivers7,amount_drivers8,amount_drivers9 andamount_drivers10 (from traffic table) have to go in the column 'to_hard'. So this is a sum of the columns amount_drivers6, amount_drivers7,amount_drivers8,amount_drivers9 andamount_drivers10 in this case. This sum must go in the column 'to_hard'.
I've tried using a case statement:
declare @AMOUNT INT=0
SELECT @AMOUNT=CASE WHEN VALUE_OF_SPEED_CATEGORIES_COLUMNS_FROM_TABLE_SPEED_CATEGORIES >ST.MAX_SPEED THEN
@AMOUNT += AMOUNT_DRIVERS_FROM_TABLE_TRAFFIC
ELSE 'DO NOTHING'
END
FROM MAX_SPEED ST INNER JOIN SPEED_CATEGORIES SC ON ST.WAY=SC.WAY
INNER JOIN TRAFFIC T ON SC.WAY=T.WAY
But I guess I have to use a while or for loop. Please help!
Thanks for the help!
Aucun commentaire:
Enregistrer un commentaire