Querying derived table in Entity Framework + using aggregates - sql

I do not even know where to start with this.
How do I query a derived table in Entity Framework?
Here is a SQL query I want to translate to Entity:
SELECT
count(question_id)
FROM
(
SELECT
question_id
FROM
user_answers
WHERE
user_id = 'xyz'
AND
correct = 1
GROUP BY
QUESTION_ID
HAVING
count(*) > 1
) as b
Can anybody provide any insight into this?
Many thanks!
Kevin

Related

Create view with JSON array based on many to many table

I have a typical table with users. I have also a many to many table where first column is UserId and second BusinessId. I want to create a view with users where their businessId will be as json.
I tried something like this:
SELECT
ISNULL(CAST(u.[Id] AS INT), 0) AS [Id]
,(SELECT BusinessId FROM [TableA].[dbo].[user_business_entities] WHERE UserId = u.Id FOR JSON AUTO) AS BusinessEntityIds
FROM
[TableA].[dbo].[core_users] u
But in view I get this:
Id
BusinessEntityIds
1
[{"BusinessId":1925},{"BusinessId":1926}]
2
[{"BusinessId":15}]
It's pretty good, but it would be best if json had only values, no key name i.e only ids without "BusinessId":
Id
BusinessEntityIds
1
[1925, 1926]
2
[15]
How can I do this?
Two quick options: First is for <=2016 and the 2nd is 2017+
Never understood why MS never provided this functionality of a simple ARRAY.
Option 1 <=2016
Select ID
,BusinessEntityIds = '['+stuff((Select concat(',',BusinessEntityIds)
From YourTable
Where ID=A.ID
For XML Path ('')),1,1,'')+']'
From YourTable A
Group By ID
Option 2 2017+
select ID,
BusinessEntityIds = '['+string_agg(BusinessEntityIds, ',') +']'
from YourTable
group by ID
Both Results Are
ID BusinessEntityIds
1 [1925,1926]
2 [15]

Efficient way to check if column has all certain values

I am using following query to show only those inspectors who have got both qualifications.
DECLARE #CertType QualificationType; --2,3
select i.InspectorID from Inspectors i
INNER JOIN (
SELECT _id.InspectorID
FROM InspectorDocs _id
WHERE _id.QualificationTypeID IN (select [QualificationTypeID] from #CertType) GROUP BY _id.InspectorID
HAVING COUNT(DISTINCT _id.QualificationTypeID) = (select count(*) from #CertType)
) as id on id.inspectorid = i.inspectorid
Is there any better way to find if column has all given values?
Schema
Inspectors: Inspectors (PK)
InspectorDocs : DocID (PK) , InspectorID (FK), QualificationTypeID (FK)
QualificationTypE : QualificationTypeID (PK)
If I'm not mistaken what you're doing is what's known as a relational division, and another (slightly non-intuitive) way to express this is the following query, which should give better performance:
select * from Inspectors i
where not exists (
select * from QualificationType c
where QualificationTypeID IN (2,3)
and not exists (
select * from InspectorDocs id
where c.QualificationTypeID = id.QualificationTypeID
and id.InspectorID = i.InspectorID))
If you want to dig deeper into this subject I recommend reading Divided We Stand: The SQL of Relational Division by Joe Celko.

How Make a Hierarchical Selection with SQL Query

I have a problem in creating a SQL Query as follows :
I Have 2 Tables with following Specification and data:
http://dc699.4shared.com/img/lgtP3N_4ce/s3/144c7252ff8/SQL1.jpg
I want to create a SQL Select Query to return for me a Hierarchical Model Like this :
For example if the SID is 3 it should return for me this :
http://dc699.4shared.com/img/8UufpK2-ce/s3/144c7255af0/SQL2.jpg
Because the Num 3 in structure table related to data 7,8,9 and 9 is related to 10,11(Note that No 9 is related to 3 or in other words 9 is subset of 3)
Can anyone help me to create this Query? I have try for 2 weeks but I failed :(
Thanks so much
You can also try an Rank solution like this one
WITH Personel_Structure AS
(
SELECT [SID],MID, RANK() OVER(PARTITION BY [SID] ORDER BY MID ASC) AS POS
FROM Structure
WHERE [SID] = 3
)
SELECT [SID],MID
FROM Personel_Structure
ORDER BY POS ASC
I have script this against the structure table if you need to do a join to the personel table that should be easy from here. Just join the the tables in the CTE.
Untested answer, and it does not include the root member for readability and because your examples in the question and comments are inconsistent. This should get you going.
I made the query starting with root = 1
WITH members (id)
AS
(SELECT MID as id FROM structure WHERE SID = 1
UNION ALL
SELECT MID as id
FROM members
INNER JOIN structure ON (members.id = structure.SID)
)
SELECT members.ID FROM members;
members is the intermediary table created by the CTE (WITH...)
sqlfiddle

SQL Server : Update Flag on Max Date on Foreign key

I'm trying to do this update but for some reason I cannot quite master SQL sub queries.
My table structure is as follows:
id fk date activeFlg
--- -- ------- ---------
1 1 04/10/11 0
2 1 02/05/99 0
3 2 09/10/11 0
4 3 11/28/11 0
5 3 12/25/98 0
Ideally I would like to set the activeFlg to 1 for all of the distinct foreign keys with the most recent date. For instance after running my query id 1,3 and 4 will have an active flag set to one.
The closest thing I came up with was a query returning all of the max dates for each distinct fk:
SELECT MAX(date)
FROM table
GROUP BY fk
But since I cant even come up with the subquery there is no way I can proceed :/
Can somebody please give me some insight on this. I'm trying to really learn more about sub queries so an explanation would be greatly appreciated.
Thank you!
You need to select the fk to and then restrict by that, so
SELECT fk,MAX(date)
FROM table
GROUP BY fk
To
With Ones2update AS
(
SELECT fk,MAX(date)
FROM table
GROUP BY fk
)
Update table
set Active=1
from table t
join Ones2update u ON t.fk = u.fk and t.date = u.date
also I would test first so do this query first
With Ones2update AS
(
SELECT fk,MAX(date)
FROM table
GROUP BY fk
)
selct fk, date, active
from table t
join Ones2update u ON t.fk = u.fk and t.date = u.date
to make sure you are getting what you expect and I did not make any typos.
Additional note: I use a join instead of a sub-query -- they are logically the same but I always find joins to be clearer (once I got used to using joins). Depending on the optimizer they can be faster.
This is the general idea. You can flesh out the details.
update t
set activeFlg = 1
from yourTable t
join (
select id, max([date] maxdate
from TheForeignKeyTable
group by [date]
) sq on t.fk = sq.id and t.[date] = maxdate

How to iterate through an SQL table which "parent" and child" rows are in same table

In a table there are the columns ID, Title and ParentID. ParentID is used for the ID of the entry in the same table which is considered its parent - thus any entry in which ParentID is NULL is one which is itself a parent.
I need a query which will iterate through each parent and list any child below it (ideally with a hyphen or something to denote its subordination) does anyone know how this can be done or how to point me in the right direction?
(I've looked into T-SQL and read many similar online questions however my SQL isn't quite sharp enough to make sense of it, so I'd greatly appreciate some pointers!)
Here you are!
WITH n(ID, Title) AS
(SELECT ID, Title
FROM YourTable
WHERE ID = (SELECT TOP 1 ID FROM YourTable WHERE ParentID IS NULL)
UNION ALL
SELECT nplus1.ID, nplus1.Title
FROM YourTable as nplus1, n
WHERE n.ID = nplus1.ParentID)
SELECT ID, Title FROM n
To get hierarchy data from self-referencing table, you can use WITH syntax in sql 2008
WITH n(ID) AS
(SELECT ID FROM YourTable
UNION ALL
SELECT nplus1.ID
FROM YourTable as nplus1, n
WHERE n.ID = nplus1.ParentID)
SELECT ID FROM n