Columns are not populating numbers - row

I have some data from weeks that I am trying to populate into the graph, the columns that should be displaying the data for 5 weeks and then the total. Please see the picture. Instead they all come up empty.
enter image description here
I know it is a case statement to here is what I have.
SET DATEFIRST 1;
DECLARE #mEnd DATETIME;
DECLARE #InputDate DATETIME;
DECLARE #EndOfMonthTemp DATETIME;
SET #EndOfMonth = #mEnd;
SET #StartWeek1 = #InputDate;
SET #StartWeek2 = DATEADD(day, 8-(DATEPART(weekday, #StartWeek1)), #StartWeek1);
SET #StartWeek3 = CASE WHEN DATEADD(day, 7, #StartWeek2) > #EndOfMonth THEN #EndOfMonth ELSE DATEADD(day, 7, #StartWeek2) END;
SET #StartWeek4 = CASE WHEN DATEADD(day, 7, #StartWeek3) > #EndOfMonth THEN #EndOfMonth ELSE DATEADD(day, 7, #StartWeek3) END;
SET #StartWeek5 = CASE WHEN DATEADD(day, 7, #StartWeek4) > #EndOfMonth THEN #EndOfMonth ELSE DATEADD(day, 7, #StartWeek4) END;
SET #StartWeek6 = CASE WHEN DATEADD(day, 7, #StartWeek5) > #EndOfMonth THEN #EndOfMonth ELSE DATEADD(day, 7, #StartWeek5) END;
SET #InputDate = DATEFROMPARTS(YEAR(#InputDate), MONTH(#InputDate), 1)
SET #mEnd = EOMONTH(#InputDate)
DECLARE #StartWeek1 DATETIME
DECLARE #StartWeek2 DATETIME
DECLARE #StartWeek3 DATETIME
DECLARE #StartWeek4 DATETIME
DECLARE #StartWeek5 DATETIME
DECLARE #StartWeek6 DATETIME
DECLARE #EndOfMonth DATETIME
SET #EndOfMonthTemp = DATEADD(day, 1, EOMONTH(#InputDate)) -- add a day
SET #EndOfMonth = DATEADD(second, -1, #mEnd); -- subtract a second
Select
filled
, SentDate_1
, Program
, COUNT(CASE WHEN EDISCLOSEDTRK_SentDate_1 BETWEEN #StartWeek1 AND DATEADD(second, -1, #StartWeek2) THEN 1 ELSE NULL END) AS [Week1]
, COUNT(CASE WHEN EDISCLOSEDTRK_SentDate_1 BETWEEN #StartWeek2 AND DATEADD(second, -1, #StartWeek3) THEN 1
, COUNT(CASE WHEN EDISCLOSEDTRK_SentDate_1 BETWEEN #StartWeek3 AND DATEADD(second, -1, #StartWeek4) THEN 1 ELSE NULL END) AS [Week3]
, COUNT(CASE WHEN EDISCLOSEDTRK_SentDate_1 BETWEEN #StartWeek4 AND DATEADD(second, -1, #StartWeek5) THEN 1
, COUNT(CASE WHEN EDISCLOSEDTRK_SentDate_1 BETWEEN #StartWeek5 AND DATEADD(second, -1, #EndOfMonth) THEN 1 ELSE NULL END) AS [Week5]
, COUNT(*) AS [Total]
from
VADER
INNER JOIN WALKER E1 ON (E5.GUID = E1.GUID)
WHERE
SentDate_1 >= DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE()),0) and Program = 'My results'
GROUP BY filled
,SentDate_1
,Program
Should look like this.
[enter image description here](https://i.stack.imgur.com/BLT38.png)
Thank you in advance!!!!

Related

Django update rows base on order in queryset

I have a simple django model
class Item(Model):
name = CharField()
rank = PositiveIntegerField()
created_at = DateField(auto_now_add=True)
I want to update the object rank based on their order when sorted by a field (name or created_at)
e.g. when ordering by name
[("Pen", 0, "2021-05-04"), ("Ball", 0, "2021-05-04")] => [("Pen", 1, "2021-05-04"), (Ball, 0, "2021-05-04")]
I already know I can do this using bulk_update but it means I have to fetch the objects in memory
items = Items.objects.order_by("name")
for i, item in enumerate(items):
item.rank = i
Item.objects.bulk_update(items, ["rank"])
I was wondering if there is a way to do it with 1 query directly in the database, without having to fetch the data
CREATE TABLE items (
id serial PRIMARY KEY,
name VARCHAR ( 50 ) UNIQUE NOT NULL,
rank smallint
);
insert into items(id, name, rank) values (1, 'A', 0);
insert into items(id, name, rank) values (2, 'B', 0);
insert into items(id, name, rank) values (3, 'C', 0);
select * from items;
id
name
rank
1
A
0
2
B
0
3
C
0
UPDATE items
SET rank=calculated.calc_rank
FROM
(SELECT id AS calc_id,
(ROW_NUMBER() OVER (
ORDER BY name ASC)) AS calc_rank
FROM items) AS calculated
WHERE items.id = calculated.calc_id;
select * from items;
id
name
rank
1
A
1
2
B
2
3
C
3
And perform raw SQL for Django:
sql = '''
UPDATE items
SET rank=calculated.calc_rank
FROM
(SELECT id AS calc_id,
(ROW_NUMBER() OVER (
ORDER BY name ASC)) AS calc_rank
FROM items) AS calculated
WHERE items.id = calculated.calc_id
'''
with connection.cursor() as cursor:
cursor.execute(sql)

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;

Calculating Overlapping time-span count in SQL Server 2008 R2

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?

Get First Date and Last Date of Current Quarter in Python?

How can i get the Current Quarter year and then First Date and last Date of Current Quarter Year in Python?
i want by importing datetime
import datetime
People look into Stack overflow need straight forward answer and which should be very simple. Which ever link you provided it having lot of Comments. SO, users has to go through all the comments to find correct answer. I am writing simple and straight forward answer.
I believe that none of the current answers are still valid in Python 3, so since this is the top hit in google for first and last day of quarter, I will provide a solution that works in Python 3 (mostly Ahmet's with // instead of /):
from datetime import date as date_class
from datetime import timedelta, datetime
def get_quarter(p_date: date_class) -> int:
return (p_date.month - 1) // 3 + 1
def get_first_day_of_the_quarter(p_date: date_class):
return datetime(p_date.year, 3 * ((p_date.month - 1) // 3) + 1, 1)
def get_last_day_of_the_quarter(p_date: date_class):
quarter = get_quarter(p_date)
return datetime(p_date.year + 3 * quarter // 12, 3 * quarter % 12 + 1, 1) + timedelta(days=-1)
assert get_quarter(datetime(year=2021, month=10, day=5).date()) == 4
assert get_quarter(datetime(year=2020, month=9, day=25).date()) == 3
assert get_quarter(datetime(year=2020, month=12, day=11).date()) == 4
assert get_quarter(datetime(year=2020, month=1, day=2).date()) == 1
assert get_first_day_of_the_quarter(datetime(2020, 10, 5).date()) == datetime(2020, 10, 1)
assert get_first_day_of_the_quarter(datetime(2020, 9, 25).date()) == datetime(2020, 7, 1)
assert get_first_day_of_the_quarter(datetime(2020, 12, 11).date()) == datetime(2020, 10, 1)
assert get_first_day_of_the_quarter(datetime(2020, 1, 2).date()) == datetime(2020, 1, 1)
assert get_last_day_of_the_quarter(datetime(2020, 10, 5).date()) == datetime(2020, 12, 31)
assert get_last_day_of_the_quarter(datetime(2020, 9, 25).date()) == datetime(2020, 9, 30)
assert get_last_day_of_the_quarter(datetime(2020, 12, 11).date()) == datetime(2020, 12, 31)
assert get_last_day_of_the_quarter(datetime(2020, 1, 2).date()) == datetime(2020, 3, 31)
assert get_last_day_of_the_quarter(datetime(2020, 5, 6).date()) == datetime(2020, 6, 30)
Having the first day is the same with #Karishh's solution. But, for the last date, Python2.7 causes a problem for fourth quarter. Because 12+1=13 and datetime does not accept 13 as a month. So you need to do some tricks to handle it.
import datetime
def get_quarter(date):
return (date.month - 1) / 3 + 1
def get_first_day_of_the_quarter(date):
quarter = get_quarter(date)
return datetime.datetime(date.year, 3 * quarter - 2, 1)
def get_last_day_of_the_quarter(date):
quarter = get_quarter(date)
month = 3 * quarter
remaining = month / 12
return datetime.datetime(date.year + remaining, month % 12 + 1, 1) + datetime.timedelta(days=-1)
Any how i found some simple solution in c# and converted it into python,
from datetime import datetime,timedelta
current_date=datetime.now()
currQuarter = (current_date.month - 1) / 3 + 1
dtFirstDay = datetime(current_date.year, 3 * currQuarter - 2, 1)
dtLastDay = datetime(current_date.year, 3 * currQuarter + 1, 1) + timedelta(days=-1)
Here's a one/two liner to get the start/end date of the current quarter.
from datetime import datetime
import math
from dateutil.relativedelta import relativedelta # requires python-dateutil
start_of_quarter = datetime(year=datetime.now().year, month=((math.floor(((datetime.now().month - 1) / 3) + 1) - 1) * 3) + 1, day=1)
end_of_quarter = start_of_quarter + relativedelta(months=3, seconds=-1)
pendulum has a much more intuitive implementation.
import pendulum
dt = pendulum.datetime(2021, 3, 23)
print(dt.first_of('quarter'))
print(dt.last_of('quarter'))
2021-01-01T00:00:00+00:00
2021-03-31T00:00:00+00:00
Building off of the answer from Krishh, but addressing several issues found:
calculating last day in Quarter 4
Wasae Shoaib's comment about raising a ValueError
TypeError with a float being passed instead of an integer
Using relativedeta instead and shifting the correctly calculated start date by three months, we end up with a much more reliable way to get at the quarter end date.
from datetime import datetime
from dateutil.relativedelta import relativedelta
current_date = datetime.now()
currQuarter = int((current_date.month - 1) / 3 + 1)
dtFirstDay = datetime(current_date.year, 3 * currQuarter - 2, 1)
dtLastDay = dtFirstDay + relativedelta(months=3, days=-1)
I did of a lot of tests to find the solution that fit my need and I will be happy if it helps someone else :
datval = fields.date.today()
if datval.month < 4 :
self.start_date = fields.date.today().replace(month=10, day=1)
self.end_date = fields.date.today().replace(month=12, day=31)
elif datval.month < 7 :
self.start_date = fields.date.today().replace(month=1, day=1)
self.end_date = fields.date.today().replace(month=3, day=31)
elif datval.month < 10 :
self.start_date = fields.date.today().replace(month=4, day=1)
self.end_date = fields.date.today().replace(month=6, day=30)
else :
self.start_date = fields.date.today().replace(month=7, day=1)
self.end_date = fields.date.today().replace(month=9, day=30)
Get start and end points for: week, month, quarter and year
https://gist.github.com/dejurin/236b398dc4b8064685702a27a3df612b
from datetime import date
from dateutil.relativedelta import relativedelta
def start_end_day(sunmon: bool = True):
today = date.today()
curr_quarter = int((today.month - 1) / 3 + 1)
dayofweek = [today.weekday(),today.isoweekday()][sunmon]
week_start = today - relativedelta(days=dayofweek)
week_end = week_start + relativedelta(days=6)
month_start = date(today.year,today.month, 1)
month_end = month_start + relativedelta(months=1, days=-1)
quarter_start = date(today.year, 3 * curr_quarter - 2, 1)
quarter_end = quarter_start + relativedelta(months=3, days=-1)
year_start = date(today.year, 1, 1)
year_end = year_start + relativedelta(years=1, days=-1)
return ((week_start,week_end),(month_start,month_end),(quarter_start,quarter_end),(year_start,year_end))
"""
Current date: 18/02/2022
"""
"""
((datetime.date(2022, 2, 13), datetime.date(2022, 2, 19)),
(datetime.date(2022, 2, 1), datetime.date(2022, 2, 28)),
(datetime.datetime(2022, 1, 1, 0, 0), datetime.datetime(2022, 3, 31, 0, 0))
(datetime.date(2022, 1, 1), datetime.date(2022, 12, 31)))
"""

Using query builder to return an average in a single query

Okay, so I want to return an average transaction size in query builder. This is definitely not my forte so hoping I can find some help on this:
This is what I have:
I need to get total transactions (i.e. $100)
I need to get count of transaction (i.e. 10)
The above would represent an average transaction value of $10
Now to do this in query builder:
Step 1: get the total:
$qb = $this->transactionRepository->createQueryBuilder('u');
$qb ->add('select','SUM(u.amount)')
->where('u.status = :status')
->andWhere('u.type = :type')
->andWhere('u.identity = :identity')
->setParameter('status' , 1)
->setParameter('type' , 1)
->setParameter('identity' , 1);
$total = $qb
->getQuery()
->getSingleScalarResult();
Step 2, get the total transactions:
$qb = $this->transactionRepository->createQueryBuilder('u');
$qb ->add('select','COUNT(u.amount)')
->where('u.status = :status')
->andWhere('u.type = :type')
->andWhere('u.identity = :identity')
->setParameter('status' , 1)
->setParameter('type' , 1)
->setParameter('identity' , 1);
$transaction_count = $qb
->getQuery()
->getSingleScalarResult();
Step 3: To get the average:
$total/$transaction_count
So my question is this, is it possible to do this in a single query?
Ok this was simpler than I thought:
$qb = $this->transactionRepository->createQueryBuilder('u');
$qb ->add('select','SUM(u.total)/COUNT(u.amount)')
->where('u.status = :status')
->andWhere('u.type = :type')
->andWhere('u.identity = :identity')
->setParameter('status' , 1)
->setParameter('type' , 1)
->setParameter('identity' , 1);
$transaction_count = $qb
->getQuery()
->getSingleScalarResult();