I would like to see how many times someone has scored more than two goals (first subquery) and how many goals in total the same person scored (second subquery).
But I don't know how to 'join' both subquery in a proper way.
SELECT o2.aantal,o3.gesc,
p.persid,p.voornaam,p.tussenvoegsel,p.achternaam
FROM
( SELECT o.persid, count(o.gesc) AS aantal
FROM opstelere o where o.gesc>2
GROUP BY o.persid ) AS o2,
(select o.persid,sum(o.gesc) as gesc from opstelere o ) as o3
JOIN personen AS p ON p.persid = o3.persid
ORDER BY aantal desc,gesc asc,achternaam asc
Try a simple group by:
SELECT
aantal,
gesc,
persid,
voornaam,
tussenvoegsel,
achternaam,
count(o.gesc) AS aantal
FROM opstelere o
GROUP BY
aantal,
gesc,
persid,
voornaam,
tussenvoegsel,
achternaam
HAVING count(o.gesc) > 2
ORDER BY aantal desc, gesc, achternaam
Related
Table gr has 2 fields named ph and flag
Table ep has a field named ph
Now I need to check that for count of ph>20 in ep I should get a count of 0 for flag in the gr table if flag <> 'Y'
I have written two separate queries and need to know how to join them
select ph,count(*) from ep
group by ph
having count(*)>20
the results of this should be checked with gr table
Using inner join ON ep.ph = gr.ph and gr.flag<> 'Y':
select gr.ph, gr.cnt
from
(select ph, flag, count(*) cnt
from gr
group by ph, flag
) gr
inner join
( select ph,count(*) from ep
group by ph
having count(*)>20
) ep ON ep.ph = gr.ph and gr.flag<> 'Y'
where gr.cnt!=0 --find where count is not 0
I have two tables table1 and table2. Each table contains a column with itemPrice. I need to add the two columns together.
The SQL query below returns the correct SUM.
SELECT SUM(item1+ item2) FROM
(select SUM(t1.itemPrice) item1 from table1 t1 WHERE t1.userid=='jonh') tableA
CROSS JOIN
(select SUM(t2.itemPrice) item2 from table2 t2 WHERE t1.userid=='jonh') tableB
I am not been lazy but the above query has so many SUM functions that I don't know where to start to write LINQ queries.
Can anyone help?
Ceci,
Hopefully this will give you what you want...
from f in (
from x in ( from t1 in Table1
where t1.Userid.Equals("John")
select new { Userid = t1.Userid }
).Distinct()
select new { item1 = ( from z in Table1
where z.Userid.Equals("John")
select z.ItemPrice ).Sum() ??0 ,
item2 = ( from z in Table2
where z.Userid.Equals("John")
select z.ItemPrice ).Sum() ??0 }
) select new { total = f.item1 + f.item2 }
In the case where there are no records for "john" in one table, it will bring back a 0 and sum up the other tables.
hope this helps.
I am giving here part of the query I am executing:
SELECT SUM(ParentTable.Field1),
(SELECT SUM(ChildrenTable.Field1)
FROM ChildrenRable INNER JOIN
GrandChildrenTable ON ChildrenTable.Id = GrandChildrenTable.ChildrenTableId INNER JOIN
AnotherTable ON GrandChildrenTable.AnotherTableId = AnotherTable.Id
WHERE ChildrenTable.ParentBaleId = ParentTable.Id
AND AnotherTable.Type=1),
----
FROM ParentTable
WHERE some_conditions
Relationships:
ParentTable -> ChildrenTable = 1-to-many
ChildrenTable -> GrandChildrenTable = 1-to-many
GrandChildrenTable -> AnotherTable = 1-to-1
I am executing this query three times, while changing only the Type condition, and here are the results:
Number of records that are returned:
Condition Total execution time (ms)
Type = 1 : 973
Type = 2 : 78810
Type = 3 : 648318
If I execute just the inner join query, here is the count of joined records:
SELECT p.Type, COUNT(*)
FROM CycleActivities ca INNER JOIN
CycleActivityProducts cap ON ca.Id = CAP.CycleActivityId INNER JOIN
Products p ON cap.ProductId = p.Id
GROUP BY p.Type
Type
---- -----------
1 55152
2 13401
4 102730
So, why would the query with Type = 1 condition execute much faster than the query with Type = 2, although it is querying 4x larger resultset (Type is tinyint)?
The way your query is written instructs SQL Server to execute the sub-query with JOIN for every row of the output.
This way it should be faster, if I understand what you want correctly (UPDATED):
with cte_parent as (
select
Id,
SUM (ParentTable.Field1) as Parent_Sum
from ParentTable
group by Id
),
cte_child as (
SELECT
Id,
SUM (ChildrenTable.Field1) as as Child_Sum
FROM ChildrenRable
INNER JOIN
GrandChildrenTable ON ChildrenTable.Id = GrandChildrenTable.ChildrenTableId
INNER JOIN
AnotherTable ON GrandChildrenTable.AnotherTableId = AnotherTable.Id
WHERE
AnotherTable.Type=1
AND
some_conditions
GROUP BY Id
)
select cte_parent.id, Parent_Sum, Child_Sum
from parent_cte
join child_cte on parent_cte.id = child_cte.id
My Stored Procedure takes a very long time to execute.
Can anyone suggest me what I can do to speed up the stored procedure, apart from using some good practices for writing down the queries.
I've heard about creating indices, but I'm not sure what are they.
Please suggest all the best ways to speed up my queries.
Thanks
CREATE PROCEDURE [dbo].[usp_GetAlternates]
(
#NNumber CHAR(11) ,
#pid INT ,
#pbmid INT
)
AS
BEGIN
TRUNCATE TABLE TempTherapeuticAlt
INSERT INTO TempTherapeuticAlt
SELECT NULL AS MedicationID ,
PR.ePrescribingName AS MedicationName ,
U.Strength AS MedicationStrength ,
FRM.FormName AS MedicationForm ,
PR.DEAClassificationID AS DEASchedule ,
NULL AS NDCNumber
FROM Product PR
JOIN ( SELECT MP.MarketedProductID
FROM table2 TCTSP
JOIN table3 MP ON MP.SpecificProductID = TCTSP.SpecificProductID
JOIN ( SELECT TCTSP.TherapeuticConceptTreeID
FROM table3 MP
JOIN table2 TCTSP ON MP.SpecificProductID = TCTSP.SpecificProductID
JOIN ( SELECT
PR.MarketedProductID
FROM
table4 PA
JOIN Product PR ON PA.ProductID = PR.ProductID
WHERE
PA.NDC11 = #NNumber
) PAPA ON MP.MarketedProductID = PAPA.MarketedProductID
) xxx ON TCTSP.TherapeuticConceptTreeID = xxx.TherapeuticConceptTreeID
) MPI ON PR.MarketedProductID = MPI.MarketedProductID
JOIN ( SELECT P.ProductID ,
O.Strength ,
O.Unit
FROM Product AS P
INNER JOIN table3 AS M ON P.MarketedProductID = M.MarketedProductID
INNER JOIN table5 AS S ON M.SpecificProductID = S.SpecificProductID
LEFT OUTER JOIN table6 AS O ON S.SpecificProductID = O.SpecificProductID
GROUP BY P.ProductID ,
O.Strength ,
O.Unit
) U ON PR.ProductID = U.ProductID
JOIN ( SELECT PA.ProductID ,
S.ScriptFormID ,
F.Code AS NCPDPScriptFormCode ,
S.FormName
FROM table4 AS PA
INNER JOIN table7 AS S ON PA.NCPDPScriptFormCode = S.NCPDPScriptFormCode
INNER JOIN table8 AS F ON S.FormName = F.FormName
GROUP BY PA.ProductID ,
S.ScriptFormID ,
F.Code ,
S.FormName
) FRM ON PR.ProductID = FRM.ProductID
GROUP BY PR.ePrescribingName ,
U.Strength ,
FRM.FormName ,
PR.DEAClassificationID
ORDER BY pr.ePrescribingName
SELECT LL.ProductID AS MedicationID ,
temp.MedicationName ,
temp.MedicationStrength ,
temp.MedicationForm ,
temp.DEASchedule ,
temp.NDCNumber ,
fs.[ReturnFormulary] AS FormularyStatus ,
copay.CopaTier ,
copay.FirstCopayTerm ,
copay.FlatCopayAmount ,
copay.PercentageCopay
FROM TempTherapeuticAlt temp
OUTER APPLY ( SELECT TOP 1
ProductID
FROM Product
WHERE ePrescribingName = temp.MedicationName
) AS LL
OUTER APPLY function1(#pid, LL.ProductID, #pbmid) AS fs
OUTER APPLY function2(LL.ProductID, #pbmid) AS copay
ORDER BY LL.ProductID
TRUNCATE TABLE TempTherapeuticAlt
END
GO
Here are a few:
You should have indexes for every column in a WHERE clause. See
your SQL language for how to do it.
Learn how to EXPLAIN PLAN and see what's slow.
Stored procedure languages are functional, not set based. Use JOIN and don't fall into the (n+1) query/iteration trap.
Understand how using certain functions force you to TABLE SCAN in a WHERE clause.
I currently have a stored procedure which returns data and displayed in my report viewer but my issue is that i check to see if students attended to class or not and i have
COALESCE(A.Attended, 0)AS Attended
This returns 1 if they attended and 0 if not - in my report it only shows 1 or 0 even though they could have attended more than once. How can i cast this to an int to get the right total.
thanks
WHOLE QUERY:
SELECT
P.PartyId,
COUNT(COALESCE(A.Attended, 0))AS Attended,
COUNT(DISTINCT H.HearingId) AS Hearings,
O.OfficeName As OfficeName,
CO.Name,
P.FirstName AS FirstName,
P.LastName AS LastName,
P.BirthDate AS DOB
FROM Activity A
INNER JOIN ActivityType AT On A.ActivityTypeId = AT.ActivityTypeId
INNER JOIN ActivityEntry AE ON A.ActivityEntryId = AE.ActivityEntryId
INNER JOIN HearingEntry HE ON CAE.HearingEntryId = HE.HearingEntryId
INNER JOIN Hearing H ON HE.HearingEntryId = H.HearingEntryId
INNER JOIN [Case] C ON H.CaseId = C.CaseId
INNER JOIN CaseOffice CO ON C.CaseId = CO.CaseId AND AE.OfficeId = CO.OfficeId
INNER JOIN Office O ON CO.OfficeId = O.OfficeId
INNER JOIN Attended A ON H.HearingId = A.HearingId
INNER JOIN Party P ON A.PartyId = P.PartyId
WHERE HP.PartyId = P.PartyId AND AE.OfficeId = #OfficeId AND(H.HearingDate >= #BeginDate AND (H.HearingDate <= #EndDate OR H.HearingDate IS NULL)) AND HE.HearingEntryId = CAE.HearingEntryId
GROUP BY P.PartyId, A.Attended, O.OfficeName,CO.Name,P.FirstName, P.LastName,P.BirthDate
I guess you mean that A.Attented is a bit and you want it to be a int, so that you can aggregate later?
You can cast to a bit to an int like this:
CAST(A.Attented AS INT)
Or in this case:
COALESCE(CAST(A.Attended AS INT), 0) AS Attended
You need to SUM by Attended .
SELECT
P.PartyId,
(SUM(COALESCE(A.Attended, 0)))AS Attended,
COUNT(DISTINCT H.HearingId) AS Hearings,
O.OfficeName As OfficeName,
CO.Name,
P.FirstName AS FirstName,
P.LastName AS LastName,
P.BirthDate AS DOB
FROM Activity A
INNER JOIN ActivityType AT On A.ActivityTypeId = AT.ActivityTypeId
INNER JOIN ActivityEntry AE ON A.ActivityEntryId = AE.ActivityEntryId
INNER JOIN HearingEntry HE ON CAE.HearingEntryId = HE.HearingEntryId
INNER JOIN Hearing H ON HE.HearingEntryId = H.HearingEntryId
INNER JOIN [Case] C ON H.CaseId = C.CaseId
INNER JOIN CaseOffice CO ON C.CaseId = CO.CaseId AND AE.OfficeId = CO.OfficeId
INNER JOIN Office O ON CO.OfficeId = O.OfficeId
INNER JOIN Attended A ON H.HearingId = A.HearingId
INNER JOIN Party P ON A.PartyId = P.PartyId
WHERE HP.PartyId = P.PartyId AND AE.OfficeId = #OfficeId AND(H.HearingDate >= #BeginDate AND (H.HearingDate <= #EndDate OR H.HearingDate IS NULL)) AND HE.HearingEntryId = CAE.HearingEntryId
GROUP BY P.PartyId, O.OfficeName,CO.Name,P.FirstName, P.LastName,P.BirthDate