Calculating Overlapping time-span count in SQL Server 2008 R2 - concurrency

I need to get concurrency count in SQL Server 2008 R2. I have a provider who will for a date will supervise certain records, I need to get count for overlapping times. e.g
Sample data:
DECLARE #Concurrency Table
(
[ConcurrencyTimeID] BigInt,
[SupervisingProviderID] Int,
[SupervisingProviderFirstName] Varchar(50),
[SupervisingProviderLastName] Varchar(50),
[DateOfService] DateTime,
[PatientFirstName] Varchar(50),
[PatientLastName] Varchar(50),
[StartTime] Time,
[StopTime] Time,
[DStartTime] DateTime,
[DStopTime] DateTime,
[IsNextDay] Bit
)
INSERT INTO #Concurrency
(
[ConcurrencyTimeID],
[SupervisingProviderID],
[SupervisingProviderFirstName],
[SupervisingProviderLastName],
[DateOfService],
[PatientFirstName],
[PatientLastName],
[StartTime],
[StopTime],
[IsNextDay]
)
SELECT 25, 4, 'hardik', 'Patel', '05/30/2016', 'a', 'a', '8:00:00 PM', '11:00:00 PM', 0
UNION ALL SELECT 25, 4, 'hardik', 'Patel', '05/30/2016', 'b', 'b', '8:30:00 PM', '9:30:00 PM', 0
UNION ALL SELECT 25, 4, 'hardik', 'Patel', '05/30/2016', 'c', 'c', '9:00:00 PM', '11:30:00 PM', 0
UNION ALL SELECT 25, 4, 'hardik', 'Patel', '05/30/2016', 'd', 'd', '10:00:00 PM', '2:00:00 AM', 1
UNION ALL SELECT 25, 4, 'hardik', 'Patel', '05/31/2016', 'e', 'e', '1:00:00 AM', '3:00:00 AM', 0
UNION ALL SELECT 25, 4, 'hardik', 'Patel', '05/31/2016', 'f', 'f', '2:30:00 AM', '3:30:00 AM', 0
UPDATE #Concurrency
SET [DStartTime] = ( Convert(Varchar, [c].[DateOfService], 112) + Cast([c].[StartTime] AS DateTime) ),
[DStopTime] = CASE WHEN [c].[IsNextDay] = 1 THEN ( Convert(Varchar, [c].[DateOfService], 112) + Cast('23:59' AS DateTime) )
ELSE ( Convert(Varchar, [c].[DateOfService], 112) + Cast([c].[StopTime] AS DateTime) )
END
FROM #Concurrency AS [c]
My query:
SELECT [c].[SupervisingProviderID],
[ca].[Ccount]
FROM #Concurrency AS [c]
CROSS APPLY (
SELECT [Ccount] = Count(*)
FROM #Concurrency AS [c2]
WHERE [c].[DateOfService] = [c2].[DateOfService]
AND [c].[SupervisingProviderID] = [c2].[SupervisingProviderID]
AND [c].[DStartTime] <= [c2].[DStopTime]
AND [c2].[DStartTime] <= [c].[DStopTime]
) AS ca
Expected Result
At present I am getting Concurrency = 4 for Patient - A. Can anyone help me get what am I doing wrong?

Related

Remove duplicate values between arrays in BigQuery

Let's say that I have the following arrays:
SELECT ['A', 'B', 'C', 'A', 'A', 'A'] AS origin_array
UNION ALL
SELECT ['A', 'A', 'B'] AS secondary_array
And I want to remove all duplicate values between the arrays (as opposed to within the arrays), so that the final result will be:
SELECT ['C', 'A', 'A'] AS result_array
Any idea how can it be done?
Below is for BigQuery Standard SQL
#standardSQL
CREATE TEMP FUNCTION DEDUP_ARRAYS(arr1 ANY TYPE, arr2 ANY TYPE) AS ((ARRAY(
SELECT item FROM (
SELECT item, ROW_NUMBER() OVER(PARTITION BY item) pos FROM UNNEST(arr1) item UNION ALL
SELECT item, ROW_NUMBER() OVER(PARTITION BY item) pos FROM UNNEST(arr2) item
)
GROUP BY item, pos
HAVING COUNT(1) = 1
)));
WITH `project.dataset.table` AS (
SELECT ['A', 'B', 'C', 'A', 'A', 'A'] AS origin_array, ['A', 'A', 'B'] AS secondary_array
)
SELECT DEDUP_ARRAYS(origin_array, secondary_array) AS result_array
FROM `project.dataset.table`
with result
Row result_array
1 A
A
C
which is what would SELECT ['C', 'A', 'A'] AS result_array returned
If you type just UNION instead of UNION ALL it should not take the duplicate values.

Put information from a dabtabse file into lists

import sqlite3
db = sqlite3.connect('newdb.db')
team_list = ['Munster', 'Leinster', 'Ulster', 'Glasgow']
cursor = db.cursor()
for i in range(len(team_list)):
team_names = team_list[i].upper()
searchStr = '%' + team_names + '%'
cursor.execute('select * from tickets where Name LIKE ?', (searchStr,))
teams_points = cursor.fetchall()
print teams_points
cursor.close()
db.close()
This is my python code used to display all data in the table 'tickets' in newdb.db. I have a list with the team names and i want to be able to search these team names in the database and calculate information on tickets sold.
picture of database
[(u'MUNSTER', 5, u'First Round'), (u'MUNSTER', 5, u'First Round'),
(u'MUNSTER', 8, u'Second Round'), (u'MUNSTER', 10, u'Both Rounds')]
[(u'LEINSTER', 2, u'Second Round'), (u'LEINSTER', 16, u'First Round'),
(u'LEINSTER', 5, u'Both Rounds'), (u'LEINSTER', 6, u'Both Rounds'),
(u'LEINSTER', 3, u'First Round')]
[(u'ULSTER', 10, u'Second Round')]
[(u'GLASGOW', 4, u'First Round')]
Above is my output when I run the script, i want to be able put each team into a list as
team_list=['team_name', 'total first round tickets', 'second round tickets']
munster_list = ['MUNSTER', '20', '18']
leinster_list = ['LEINSTER','30','13']
ulster_list = ['ULSTER','0','10']
glasgow_list = ['GLASGOW','4','0']
so then to print the list I can just use print munster_list
Use GROUP BY to get one output row from the rows in each group. Use CASE expressions to sum up only certain values:
SELECT Name,
sum(CASE WHEN Type IN ('First Round', 'Both Rounds')
THEN Amount
ELSE 0
END) AS "first round tickets",
sum(CASE WHEN Type IN ('Second Round', 'Both Rounds')
THEN Amount
ELSE 0
END) AS "second round tickets"
FROM tickets
GROUP BY Name
ORDER BY Name;

How do I order the contents of a txt file

Hi this is the code I have at the moment which orders the following string by the age of the students 10,12,15 but how do I order it alphabetically starting with d ECT
>>> student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
>>> sorted(student_tuples, key=lambda student: student[2])
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Just sort without any key:
sorted(student_tuples)
If the names can be lower case and capitalized use:
sorted(student_tuples, key=lambda student: student[0].lower())

Complex Django Query to Create Dictionary

models.py
class Event(models.Model):
name = models.CharField(max_length=100)
date = models.DateField()
class Result(models.Model):
event = models.ForeignKey(Event)
place = models.IntegerField()
person = models.CharField(max_length=100)
gender = models.CharField(max_length=1)
score = models.IntegerField()
Event sample data:
id, name, date
1, 'event1', '2015-01-01'
2, 'event2', '2015-02-01'
3, 'event3', '2015-03-01'
Result sample data:
event_id, place, person, gender, score
1, 1, 'al', 'M', 25
1, 2, 'bob', 'M', 22
1, 3, 'cindy', 'F', 21
1, 4, 'doug', 'M', 20
2, 1, 'elen', 'F', 30
2, 2, 'frank', 'M', 28
2, 3, 'gord', 'M', 20
2, 4, 'helen', 'F', 19
I want to query this and get a dictionary containing the male and female winners (with scores) for each event:
winnersdict = {event_id: (mwinner, mscore, fwinner, fscore), ...}
In this case the resulting dictionary would be:
{1: ('al', 25, 'cindy', 21), 2: ('frank', 28, 'elen', 30). 3: (None, None, None, None)}
Right now I am doing it like this:
events = Event.objects.all().order_by('date')
winnersdict = {}
for e in events:
femalewinner = Result.objects.filter(event_id=e.id, gender='F')[:1]
if len(femalewinner) == 0:
fwinner = None
fscore = None
else:
fwinner = femalewinner[0].person
fscore = femalewinner[0].score
malewinner = Result.objects.filter(event_id=e.id, gender='M')[:1]
if len(malewinner) == 0:
mwinner = None
mscore = None
else:
mwinner = malewinner[0].person
mscore = malewinner[0].score
winnersdict[e.id] = (mwinner, mscore, fwinner, fscore)
Surely there is a smarter way. I'm going to have thousands of events, looping through this way seems terrible. If it simplified things I would also be fine with generating a separate femalewinnersdict and malewinnersdict. I'm also fine (might even prefer) if we leave the None's out of the resulting dictionary, for this case I'm not interested in events that don't have results yet.
Any ideas?
Please try following query, it would give you male/female separately.
from django.db.models import Max
male_results = Event.objects.filter(result__gender='M') \
.annotate(max_score=Max('result__score')) \
.values('name', 'result__person', 'result__score')

How to write the retrieved DB from MS SQL server into new CSV File with headers using python 2.7.6

I am trying to view the database retrieved from ms SQL server in CSV file using python with headers(column names)and without any braces and quotes. My code is as follows:
import csv
import pyodbc
outpath="path\\test1.csv"
output = open(outpath, "w")
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SIPLDT0115;DATABASE=First_eg;UID=sa;PWD=wisdom')
cursor = cnxn.cursor()
sql = "select * from First1"
cursor.execute(sql)
rows = cursor.fetchall()
desc = cursor.description
header = (desc[0][0], desc[1][0], desc[2][0], desc[3][0], desc[4][0])
print "%s %3s %s %3s %3s" % header
for row in rows:
print row
value = str(row).strip('(')
output.write(str(value.replace(')','\n')))
output.close()
f = open("path\\test1.csv").read()
print f
OUTPUT:
F_Name L_Name S_ID Branch Course
('jash', 'u', 123, 'C', 'B')
('jash', 'u', 123, 'C', 'B')
('jash', 'u', 123, 'C', 'B')
'jash', 'u', 123, 'C', 'B'
'jash', 'u', 123, 'C', 'B'
'jash', 'u', 123, 'C', 'B'
In the csv file, it was coming without headers.
I want to view the database as like a table in csv file with header. How? Is it possible? please reply yar!!