Monday, October 1, 2018

First ERDs mornings

Here is our little bakery ERD as far as we god

Here Are the diagrams for relationships

Thursday, September 27, 2018

First Python

First console

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> print("Hello")
Hello
>>> name = 'Steve'
>>> print("hello, ",name)
hello,  Steve
>>> name=input("Enter your name: ")
Enter your name: Bob
>>> print ("Hello,",name)
Hello, Bob
>>> 

Hello Bob Program

#This program takes a name as input
#and outputs a greeting
#steve C 9/27/2018

#input
#process (algorithm) --
#def of algorithm--steps needed to accomplish a task
# in the order that they need to be taken
# take inputs and turn them into outputs
#output

def main():
    #get the input
    name = input('Enter your name: ')
    # print the text and variable
    print('Hello,',name)

#call main
main()

Cube program

# user enter an integer
# output a cube of that integer
# When using numbers use eval or number type int float
def main():
    number = float(input("Enter an integer: "))
    cube=number * number * number
    print("The cube is",cube)

main()

Chaos program with additional input for user to determine number of loops

# chaos program (page 13)

def main():
    print('This program illustrates a chaotic function')
    x=float(input('Enter a number between 0 and 1: '))
    y=int(input('Enter the number of loops '))
    for i in range(y):
        x=3.9 * x *(1-x)
        print(i,x)

    

main()
            

Wednesday, September 26, 2018

Afternoon Notes

Process--Organized-- out growing current system

Figure out the scope of the database:

The database will manage business transactions to make sure they are profitable. The Database will track inventory. The database will track point of sale. The database will track customers who are willing to enter data. (loyality awards). Manage requests. Manage purchases. Security. (Query or reports, profit and loss)

Gather information:

look at documents: spiral notebooks, receipts, Forms and Reports. Procedures and manuals.

Talk interview stakeholders

Job Shadowing: exceptions

Analysis: forming requirements:

Data requirements--what data has to be in the database

Reporting requirements--kinds of reports the database must produce

security requirements--Who has access to what

Inventory: Title, Year, genre, condition, rating, artist, purchase price, purchase date, Section (location), purchased from, Description, sellprice, Album version

Point of sale: employee, Date, time, album, customer (optional), discount, type of discount, taxpercent,

--don't store calculations

Customer: (frequency) name, email, phone, dateentered, birthday

Purchase: Date, Seller info, items purchased(title, condition) price paid for each

Requests: customer info, What album or artist, Condition, Year, album versions

Business Rules--

  • Only vince can purchase albums
  • If a customer purchase 5 albums they get a 15% discount on the next album
  • Only vince can do overrides
  • Customers are encouraged to register but not required
  • Sellers are required to provide contact info
  • Default sale price is 150% of purchase price.

Classroom Notes Morning

Process: Identifying the need

--lot of transaction, secure, better track of transactions--track inventory, point of sale autonomize

Setup statement of scope

The database will track inventory, and manage point of sale, track purchasing, expenses, manage profitability. The database will track customers and sellers. track requests.

Talking to primary stakeholders

2. Gathering information

Documents Notebooks used to track sales. receipts, pricing guides, purchasing Forms and Reports Manuals, procedures,

Talk stakeholders: Vince, employees, possibly customers.

Job shadowing: exceptions

3. useful and not : Requirements

inventory : accurate, updatable, album name, price purchased, purchase date every album will as unique, conditions, press date, labels, album year, artist where purchased, genres, store location, trends--queries, reports

Point of sale: customer, method(type of payment), saleprice, discount, kind of discount, saledate, vinyl, time, gross profit/ net (generally don't store calculated fields), employee, number of items

Customer : name, contact (email), zip, phone, date entered (discount for x number of purchases)

Sellers: name, contact (email), zip, phone, date entered, id

Requests: customer, album requested, date, artist, condition, date pressed, Notes<.p>

Business Rules--

  • Default sale price is 150% of the purchase price
  • Vince can always give discounts
  • Only Vince can purchase
  • Employees can only discount with Vince's permission
  • Customers are encouraged to register but not required
  • A registered customer who makes 5 purchases gets a disount on the 6th
  • Customers must be registered to get discounts
  • A customer must register to make a request
  • Sellers must register

Wednesday, July 18, 2018

Code for MetroAltDW SSIS

--Drop Keys (foreign then primary)
--Remove Data (truncate)
--Insert data
--reapply keys (primary then foreign)

--drop constraints

   Alter table Factschedule
   drop constraint fk_Dimdate

      Alter table Factschedule
   drop constraint fk_schedule

      Alter table Factschedule
   drop constraint fk_DimRoute

      Alter table Factschedule
   drop constraint fk_Dimbus

      Alter table Factschedule
   drop constraint fk_DimEmployee

      Alter table DimEmployee
   drop constraint Pk_DimEmployee

      Alter table DimBus
   drop constraint Pk_DimBus

      Alter table Dimschedule
   drop constraint Pk_Dimschedule

      Alter table DimRoute
   drop constraint PK_DimRoute

      Alter table DimDate
   drop constraint Pk_Dimdate

   Alter table Factschedule
   Drop constraint Pk_FactSchedule
 
 --truncate tables
 truncate table Dimbus
 truncate table dimdate
 truncate table dimEmployee
 Truncate table dimroute
 truncate table dimschedule
 truncate table factschedule



 --reinsert the live data
  Insert into DimEmployee(EmployeeKey, PositionKey, 
   PositionName, EmployeeHireDate, EmployeeHourlyPayRate)
   Select e.EmployeeKey, p.PositionKey, 
   PositionName, EmployeeHireDate, EmployeeHourlyPayRate
   From MetroAlt.dbo.Employee e
   inner join MetroAlt.dbo.EmployeePosition ep
   on e.EmployeeKey=ep.EmployeeKey
   inner join MetroAlt.dbo.Position p
   on p.PositionKey=ep.PositionKey

  Insert into DimBus(BusKey, BusTypeKey, 
  BustypeDescription, BusTypePurchasePrice)
  Select b.BusKey, bt.BusTypeKey, 
  BustypeDescription, BusTypePurchasePrice
  From MetroAlt.dbo.Bus b
  inner join MetroAlt.dbo.Bustype bt
  on b.BusTypekey=bt.BusTypeKey

 Insert into Dimroute(RouteKey, BusRouteZone)
 Select BusRouteKey, BusRouteZone
 From MetroAlt.dbo.BusRoute

 Insert into dimSchedule(BusDriverShiftKey, 
 BusScheduleAssignmentKey, 
 Employeekey)
 Select BusDriverShiftKey, 
 BusScheduleAssignmentKey, 
 Employeekey
 From MetroAlt.dbo.BusScheduleAssignment

 Insert into DimDate(BusScheduleAssignmentDate, 
 BusScheduleYear, BusScheduleMonth)
 Select distinct BusScheduleAssignmentDate, 
 Year(BusScheduleAssignmentDate),
 Month(BusScheduleAssignmentDate)
 From Metroalt.dbo.BusScheduleAssignment

 Insert into FactSchedule(DimEmployeeKey, 
 DimBusKey, DimrouteKey, DimScheduleKey, 
 DimDateKey, Riders, FaresPerRoute)
 Select Distinct DimEmployeeKey, 
 DimBusKey, DimrouteKey, DimScheduleKey, 
 DimDateKey, Riders, Riders * FareAmount
 From MetroAlt.Dbo.BusScheduleAssignment bsa
 inner join DimEmployee de
 on de.EmployeeKey=bsa.EmployeeKey
 inner join dimBus db
 on db.BusKey=bsa.BusKey
 inner join Dimroute dr
 on dr.RouteKey=bsa.BusRouteKey
 inner join DimSchedule ds
 on ds.BusScheduleAssignmentKey=bsa.BusScheduleAssignmentKey
 inner join DimDate dd
 on dd.BusScheduleAssignmentDate=bsa.BusScheduleAssignmentDate
 inner join MetroAlt.dbo.Ridership r
 on r.BusScheduleAssigmentKey=bsa.BusScheduleAssignmentKey
 inner join MetroAlt.dbo.Fare f
 on f.FareKey=r.FareKey 

 --reapply the constraints
Alter table DimEmployee
Add constraint pk_DimEmployee primary key (DimEmployeeKey)

Alter table DimBus
Add constraint pk_DimBus primary key (DimBusKey)

Alter table Dimroute
Add constraint pk_DimRoute primary key (DimRouteKey)

Alter table DimSchedule
Add constraint pk_DimSchedule primary key (DimScheduleKey)

Alter table DimDate
Add constraint pk_DimDate primary key (DimDateKey)

Alter table FactSchedule
Add constraint pk_FactSchedule 
primary key (DimEmployeeKey, DimBusKey, 
DimRouteKey, DimScheduleKey, DimDateKey)

Alter table factSchedule
add constraint fk_DimEmployee foreign key (DimEmployeeKey)
   References DimEmployee(DimEmployeeKey)

Alter table factSchedule
add constraint fk_DimBus foreign key (DimbusKey)
   References DimBus(DimBusKey)

Alter table factSchedule
add constraint fk_DimRoute foreign key (DimRouteKey)
   References DimRoute(DimRouteKey)

Alter table factSchedule
add constraint fk_Schedule foreign key (DimScheduleKey)
   References DimSchedule(DimScheduleKey)

Alter table factSchedule
add constraint fk_DimDate foreign key (DimDateKey)
   References DimDate(DimDateKey)


Select * from FactSchedule

Wednesday, June 6, 2018

Admin XML and JSON assignments

--admin commands
Use MetroAlt
go
--schema management of objects
Create schema Management
Go
Create view Management.vw_AnnualRidership
As
Select year(BusscheduleAssignmentDate) [Year],
Count(riders) Total
From BusScheduleAssignment bs
inner join Ridership r
on r.BusScheduleAssigmentKey=bs.BusScheduleAssignmentKey
Group by year(BusscheduleAssignmentDate)

go
Create view Management.vw_EmployeeInfo
As
Select EmployeeFirstName, EmployeeLastName, EmployeeEmail,
PositionName, EmployeeHourlyPayRate
From Employee e
inner join EmployeePosition ep
on e.EmployeeKey=ep.EmployeeKey
inner join Position p
on p.PositionKey=ep.PositionKey
Go
Create role managementRole

Grant Select on Schema::Management to ManagementRole

Grant Select, Insert, update on Employee to ManagementRole
Grant Select, Insert, Update on EmployeePosition to Managementrole

Create login managementLogin with password='P@ssw0rd1', default_database=MetroAlt
Use MetroAlt
Create user managementUser for login managementLogin 
Alter role managementrole add member managementUser

Backup Database MetroAlt to disk='C:\backup\MetroAlt.bak'
Restore Database metroAlt from disk='C:\backups\metroAlt'

--end admin assignment

--Begin Xml

Create xml Schema Collection MaintenanceNoteSchemaCollection
As
'<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" 
           elementFormDefault="qualified" 
           targetNamespace="http://www.metroalt.com/maintenancenote" 
           xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="maintenancenote">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="title" />
        <xs:element name="note">
          <xs:complexType>
            <xs:sequence>
              <xs:element maxOccurs="unbounded" name="p" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="followup" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>'

Create table MaintenanceDetail
(
     maintenanceDetailKey int identity(1,1) primary key,
  maintenanceNotes nvarchar(255)

)

Alter table MaintenanceDetail
Drop column MaintenanceNotes

Alter table MaintenanceDetail
add MaintenanceNotes xml (MaintenanceNoteSchemaCollection)

Insert into maintenanceDetail(maintenanceNotes)
values('<?xml version="1.0" encoding="utf-8"?>
<maintenancenote xmlns="http://www.metroalt.com/maintenancenote">
  <title>Wear and Tear on Hydralic units</title>
<note>
  <p>The hydralic units are showing signs of stress</p>
  <p>I recommend the replacement of the units</p>
</note>
  <followup>Schedule replacement for June 2016</followup>
</maintenancenote>')

--will fail because title is not Title
Insert into maintenanceDetail(maintenanceNotes)
values('<?xml version="1.0" encoding="utf-8"?>
<maintenancenote xmlns="http://www.metroalt.com/maintenancenote">
  <Title>Wear and Tear on Hydralic units</Title>
<note>
  <p>The hydralic units are showing signs of stress</p>
  <p>I recommend the replacement of the units</p>
</note>
  <followup>Schedule replacement for June 2016</followup>
</maintenancenote>')

Select * from MaintenanceDetail

--extras
Select * from Employee for xml raw('Employee'), elements, root('Employees')

--end xml
--begin JSON
Select * from Busbarn for JSON auto
Select BusBarnKey, Busbarnphone, busBarnAddress as 'address.street', 
Busbarncity as 'address.city', BusBarnZipcode as 'address.zipcode'
from Busbarn for JSON Path

Alter Database MetroAlt set compatibility_Level=130

Declare @JSON nvarchar(max)
Set @JSON='{"_id" : 1, "product": "IPad", "price" : 894.50, "quantityAvailable" : 13}'
Select * from OpenJSon(@JSON)

Declare @products nvarchar(max)
Set @products='[
    {"_id" : 1, "product": "IPad", "price" : 894.50, "quantityAvailable" : 13},
    {"_id" : 2, "product": "Chrome Book", "price" : 245.99, "quantityAvailable": 23},
    {"_id" : 3, "product": "Bose Lap Top Speakers", "price" : 89.50, "quantityAvailable" : 10},
    {"_id" : 4, "product": "Blue Tooth Game Controller", "price" : 149.99, "quantityAvailable" : 3},
    {"_id" : 5, "product": "Star Wars Mouse Pad", "price" : 1.50, "quantityAvailable" : 100},
    {"_id" : 6, "product": "Dell XPS Desk Top Computer", "price" : 945.00, "quantityAvailable" : 7},
    {"_id" : 7, "product": "Microsoft Surface Pro", "price" : 1250.75, "quantityAvailable" : 9},
    {"_id" : 8, "product": "Norton Anti Virus", "price" : 75.50, "quantityAvailable": 2},
    {"_id" : 9, "product": "Mechanical Keyboard", "price" : 125.50, "quantityAvailable" : 3},
    {"_id" : 10, "product": "Android Tablet", "price" : 345.23, "quantityAvailable" : 5}
  ]'
  Select * from OpenJson(@products)
  with (
    id int '$._id',
 product nvarchar(255) '$.product',
 price decimal(8,2) '$.price',
 quantity int '$.quantityAvailable'
 )
--end JSON

Monday, June 4, 2018

Triggers

--Triggers like stored proc
--except they are triggered by an event
--insert, update, delete
--enforcing business
--every grant request should be reviewed within 2 days
--after, instead of

use Community_Assist
go
Create Trigger tr_ReveiwList on GrantRequest
after insert 
As
--check to see if table exists
if not exists
   (Select name from sys.tables
      where name='ToReview')
Begin
  Create Table ToReview
  (
      GrantRequestKey int,
   GrantRequestDate datetime,
   DateToReviewBy Date
  )
end
Declare @GrantKey int
Declare @GrantRequestDate Datetime
Declare @DateToReview Date
Select @GrantKey=GrantRequestKey, 
@GrantRequestDate=GrantRequestDate
From Inserted
Set @DateToReview=dateAdd(Day,2,@GrantRequestDate)
Insert into ToReview(GrantRequestKey, GrantRequestDate, DateToReviewBy)
Values(@GrantKey, @GrantRequestDate, @DateToReview)
go

Insert into GrantRequest(GrantRequestDate, PersonKey, GrantTypeKey, 
GrantRequestExplanation, GrantRequestAmount)
Values(GetDate(),4,1,'Hungry this morning',60)

Select * from toReview


Select * from BusinessRule

Go
Create trigger tr_CheckMaximum on GrantRequest
instead of insert
As
Declare @requestAmount money
Declare @MaxRequestAmount money
Declare @GrantType int

Select @RequestAmount=GrantRequestAmount, 
       @GrantType=GrantTypeKey
    From inserted

Select @MaxRequestAmount=GrantTypeMaximum 
       From GrantType
    Where GrantTypekey = @GrantType

If @RequestAmount > @MaxRequestAmount
Begin
       print 'Request exceeds maximum allowed'
    return
End
Else
Begin
  Insert into GrantRequest(GrantRequestDate, PersonKey, 
  GrantTypeKey, GrantRequestExplanation, GrantRequestAmount)
  Select  GrantRequestDate, PersonKey, GrantTypeKey, 
  GrantRequestExplanation, GrantRequestAmount from inserted
End

Insert into GrantRequest(GrantRequestDate, PersonKey, 
  GrantTypeKey, GrantRequestExplanation, GrantRequestAmount)
  Values(GetDate(), 6, 1, 'Need Food', 100.75)


  Select * from GrantType
Select * from GrantRequest
Select * from ToReview