Showing one-to-many relationship - excel

I am trying to present data from SQL Server in an Excel sheet so that operational users can understand the data. Here's how the data looks in SQL Server:
PersonId Name Address Role Organization
1 John Smith 123 Main St Donor Library
1 John Smith 123 Main St Member Ballet
2 Jane Doe 333 Main St Member Orchestra
As you can see the database contains a one-to-many relationship between a person and the role they play in an organization.
In my Excel I want to show the person record only once and somehow show that this person plays multiple roles and these are the roles.

There are lots of group concatenation methods out there. Some use dynamic sql and others use xml. Here's a simple one if you have a short list of roles known in advance. And this way you can control the order of the listing really easily.
select *,
(
select
substring(
coalesce(min(case when r.Role = 'Donor' then ', Donor' end), '') +
coalesce(min(case when r.Role = 'Member' then ', Member' end), '') +
...
coalesce(min(case when r.Role = 'XXXXXX' then ', XXXXXX' end), '')
, 3, 300)
from PersonRoles pr
where pr.PersonId = p.PersonId
) as Roles
from Person p
I'm not sure how organization fits into your problem but it appears to me that it's part of the role. You should be able to use pr.Role + ' ' + pr.Organization in the case logic for that.

Related

How to count foreign key objects with annotation in Django?

Hi all!
New in Django, and confused, help is appreciated!
Have three models:
class Organization(models.Model):
organization_name = models.CharField(max_length=50)
class AppealForm(models.Model):
form_name = models.CharField(max_length=50)
class Appeal(models.Model):
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
appeal_form = models.ForeignKey(AppealForm, on_delete=models.CASCADE)
applicant_name = models.CharField(max_length=150)
Objects of Organization model:
organization_name
Organization 1
Organization 2
Objects of AppealForm model:
form_name
In written form
In oral form
Objects of Appeal model:
organization
appeal_form
applicant_name
Organization 1
In written form
First and Last name
Organization 1
In oral form
First and Last name
Organization 1
In oral form
First and Last name
Organization 2
In written form
First and Last name
Organization 2
In oral form
First and Last name
I'm trying to create a table in the template, like:
Organization
Total amount of appeals
Amount of written form appeals
Amount of oral form appeals
Organization 1
3
1
2
Organization 2
2
1
1
The content in the table contents has to be retrieved from Appeal model, that is rendered to the template.
Question:
How the query look like in views.py using Appeal model?
i recommend you read about how to do complex query in django from this documents section.
Here what your query would be like:
from django.db.models import Count, Case, When, IntegerField
Appeal.objects
.values('organization')
.annotate(
total_appeals=Count('appeal_form'),
written_amount=Count(Case(
When(appeal_form__form_name="In written form", then=1),
output_field=IntegerField(),
)),
oral_amount=Count(Case(
When(appeal_form__form_name="In oral form", then=1),
output_field=IntegerField(),
)),
).order_by()
set the above query to a value and loop through it and see the results. You should get something like this
[{'organization': 'Organization 1', 'total_appeals': 3,
'written_amount': 1, 'oral_amount': 2}, {'organization':
'Organization 2', 'total_appeals': 2, 'written_amount': 1,
'oral_amount': 1}]
Explanations:
values to group by organization
Count to count the form in that organization group
we use Case to add an if condition, then=1 to return value(else return null)
the written_amount need to be integer so we set it in the output_field
conditional part in the documents https://docs.djangoproject.com/en/dev/ref/models/conditional-expressions
why you should use order_by() for grouping queries https://docs.djangoproject.com/en/4.0/topics/db/aggregation/#interaction-with-order-by

Active users and views in azure workbooks

Can someone briefly explain the differences between active users and page views in an azure workbook? I would like to get the stats of active users of a particular azure event, but the counts shown are not realistic for the provided scenario.
As per the attached image, there is only one active user, which has to be at least 3-4 and can go up to 15-16. The value displayed in Views is unrealistic though.
Your valuable inputs are highly appreciated. Thank you
if you edit the template/workbook and look at the queries you can see exactly what is going on there:
let start = startofday(ago({Metric}));
union customEvents, pageViews
| where timestamp >= start
| where name in ({Activities}) or '*' in ({Activities}) or ('%' in ({Activities}) and itemType == 'pageView') or ('#' in ({Activities}) and itemType == 'customEvent')
{OtherFilters}
| summarize Users = dcount(user_Id), Sessions = dcount(session_Id), Views = count()
| evaluate narrow()
| project Title = case(Column == 'Users', 'Active Users', Column == 'Sessions', 'Unique Sessions', 'Views'), Metric = Value, SubTitle = '━━'
views in this case, is a count of items in the tables; Views = count(),
Users is dcount(user_Id) and Sessions = dcount(session_Id)
seeing just 1 user/session implies that there's nothing automatically generating "distinct" ids for those values, so the user_Id, session_Id fields are completely empty across all rows (the one unique id being undefined in both columns)
how user and session id values get populated is very specific to what application insights sdks you are using, and how you've configured them.

making link between a person name and pronoun in GATE

Is it possible to make a link between a person name and its PRP? in GATE E.g i have document "Maria Sharapova is a tennis player from russia. She participates in international tennis tournament. She is known for winning Wimbledon, US Open and Australian Open titles as for her looks, decibel-breaking grunts and commercial savvy - all of which made her the world's highest-paid female athlete." i want to annotate the "she" as "Maria Sharapova". I have written the following JAPE rule which identifies a pattern having a PRP after a person name
Phase: Simple
Input: Lookup Token Split
Options: control = appelt
Rule:joblookup
(
({Lookup.majorType == person_first}|
{Lookup.majorType == person_full})
({Token.kind==word})+
{Split.kind==internal}
{Token.category==PRP}
):sameathlete
-->
:sameathlete.sameAthlete1 = {kind="athlete", rule="same-athlete"}
How can i make the annotation that from She means we are talking about the same person whose name is mentioned 1 or 2 sentence before??
Please help
Have you tried Co-reference PR for gate?

Get permissions for stored procedure in sybase

How do I get the granted permissions for a stored procedure in sybase?
It depends on the form that you want that info in.
If you are writing SQL for some internal purpose, and you need that info as data for it, Kolchanov's answer is correct.
If you are merely performing DBA functions, then any number of DBA GUI tools (SybaseCentral comes with the CD; DBArtisan is much better) provide that info via an explorer window and clicks
If you only have character based access, use
sp_helprotect proc_name
Link to Sybase Online Manuals
Then go to: Adaptive Server Enterprise 15.5/Reference Manual: Procedures, nd follow the explorer.
If I wanted to check the permissions for object "whatever_[table|procedure]", I would run the following query:
Example for "whatever" being a table
Displaying result for:
---------------------
select permission = a.name
from master.dbo.spt_values a
, master.dbo.spt_values b
, sysprotects p
, sysobjects o
where a.type = "T"
and a.number = p.action
and b.type = "T"
and b.number = (p.protecttype + 204)
and o.id = p.id
and o.name = 'whatever_table'
permission
----------------------------
References
Select
Insert
Delete
Update
5 Row(s) affected
Example for "whatever" being a stored procedure
Displaying result for:
---------------------
select permission = a.name
from master.dbo.spt_values a
, master.dbo.spt_values b
, sysprotects p
, sysobjects o
where a.type = "T"
and a.number = p.action
and b.type = "T"
and b.number = (p.protecttype + 204)
and o.id = p.id
and o.name = 'whatever_procedure'
permission
----------------------------
Execute
1 Row(s) affected
Adaptive Server Enterprise 15.5 > Reference Manual: Tables > System Tables
sysprotects
sysprotects contains information on permissions that have been granted to, or revoked from, users, groups, and roles.
http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc36274.1550/html/tables/X16615.htm

How to reference one foreign key column with multiple primary key column

I am creating BOOK_Issue table which will contain id of person to whom the book is issued.
i have a column name user_id witch will contain ids from tbl_student as well as tbl_faculty. so how to set user_id field of book_issue table with reference to two primary key columns.
Your database schema is not correct.
If you expect unique IDs then they should be in one table.
You can create a table with all the users, and have a column to set their type (student, faculty). Then create 2 different tables for each type that has the proper information for each user based on their type.
Create a "person" superclass that can be either of type "student" or type "faculty". Reference this from the BOOK_Issue table instead.
Basically to create this relationship, you'll need one unique ID that spans both "student" and "faculty". Put this in a table (tbl_person?) and have each row in tbl_student and tbl_faculty reference this new table. It's probably also best to then pull out the fields present in both tbl_student and tbl_faculty and put them in this new supertable instead.
You can solve the problem by either having an extra column in BOOK_Issue table, next to user_id, which indicates if this is a Student ID or a Faculty ID.
Alternatively, the IDs themselves may readily include some pattern which indicate their nature (for example no all faculty Ids may start with say "UC", and none of the student Id are so).
The two solutions above then allow using queries similar to the following
SELECT B.*,
CASE B.BorrowerType -- could be LEFT(user_id, 2) etc...
WHEN 'S' THEN S.Name
WHEN 'F' Then F.Name
END As Name,
CASE B.BorrowerType
WHEN 'S' THEN S.PhoneNumber
WHEN 'F' Then F.Phone -- Note that these constructs allow
-- mapping distinct columns names etc.
END As PhoneNr
FROM BOOK_Issue B
LEFT JOIN tbl_student S ON B.BorrowerType = 'S' AND B.user_id = S.id
LEFT JOIN tbl_faculty F ON B.BorrowerType = 'F' AND B.user_id = F.id
WHERE B.DueDate < '11/23/2009' -- or some other condition
This can get a bit heavy when we need to get multiple columns from the student/faculty tables. A possible alternative is a UNION, but this would then cause the repeating of the search clause.
Finally, the best solution but not avaible on all DBMS is a sub-query driven by an "IF B.BorrowerType = 'S' " condition.
This should be your table design:
FacultyTable (FacultyID, FacultyName)
StudentsTable (StudentID, StudentName, FacultlyID, ...)
BookTable (BookID, BookName, ...)
UsersTable(UserID, UserName, UserPassword, StudentID, LastLogin, ...)
Now this is the main thing:
BookIssedTable(BookIssedID, BookID, UserID)
//This table tells me that a book of "BookID was issued to a user of "UserID"
//this can be better for this is certainly a great improvement from the initial design.

Resources