I've this query working fine. I need to have the sum of the column "piedini". Can you help me to undestand how to do? I obtain X row for each "Lunghezza" (lenght) that the query find. I'm not interested to this field but only to the sum o column "piedini" created from the CASE SUM.
SELECT
EXTRAMAG.PRS_LUNGHEZZA,SUM(RIGHEDOCUMENTI.QTAGEST) AS TAVOLI, CASE WHEN EXTRAMAG.PRS_LUNGHEZZA < '2000' THEN SUM(RIGHEDOCUMENTI.QTAGEST)*4 ELSE SUM(RIGHEDOCUMENTI.QTAGEST)*6 END AS PIEDINI
FROM dbo.TESTEDOCUMENTI
INNER JOIN dbo.ANAGRAFICACF
ON CODCLIFOR=CODCONTO
INNER JOIN dbo.RIGHEDOCUMENTI
ON PROGRESSIVO=IDTESTA AND TOTNETTORIGA <>'0' AND RIGHEDOCUMENTI.DESCRIZIONEART LIKE '%TAVOL%'
INNER JOIN dbo.EXTRAMAG
ON RIGHEDOCUMENTI.CODART=EXTRAMAG.CODART
LEFT JOIN .dbo.ANAGRAFICAAGENTI
ON CODAGENTE=CODAGENTE1
LEFT JOIN dbo.TABPAGAMENTI
ON CODPAGAMENTO = CODICE
WHERE dbo.TESTEDOCUMENTI.DOCCHIUSO = '0' AND dbo.TESTEDOCUMENTI.BLOCCATO = '0' AND dbo.TESTEDOCUMENTI.TIPODOC = 'ORC' AND TESTEDOCUMENTI.DATACONSEGNA BETWEEN DATEADD(DAY, -60, GETDATE()) AND GETDATE()
GROUP BY EXTRAMAG.PRS_LUNGHEZZA
Try the below :
select sum(PIEDINI) from (
SELECT XTRAMAG.PRS_LUNGHEZZA,SUM(RIGHEDOCUMENTI.QTAGEST) AS TAVOLI, CASE WHEN EXTRAMAG.PRS_LUNGHEZZA < '2000' THEN SUM(RIGHEDOCUMENTI.QTAGEST)*4 ELSE SUM(RIGHEDOCUMENTI.QTAGEST)*6 END AS PIEDINI
FROM dbo.TESTEDOCUMENTI
INNER JOIN dbo.ANAGRAFICACF
ON CODCLIFOR=CODCONTO
INNER JOIN dbo.RIGHEDOCUMENTI
ON PROGRESSIVO=IDTESTA AND TOTNETTORIGA <>'0' AND RIGHEDOCUMENTI.DESCRIZIONEART LIKE '%TAVOL%'
INNER JOIN dbo.EXTRAMAG
ON RIGHEDOCUMENTI.CODART=EXTRAMAG.CODART
LEFT JOIN .dbo.ANAGRAFICAAGENTI
ON CODAGENTE=CODAGENTE1
LEFT JOIN dbo.TABPAGAMENTI
ON CODPAGAMENTO = CODICE
WHERE dbo.TESTEDOCUMENTI.DOCCHIUSO = '0' AND dbo.TESTEDOCUMENTI.BLOCCATO = '0' AND dbo.TESTEDOCUMENTI.TIPODOC = 'ORC' AND TESTEDOCUMENTI.DATACONSEGNA BETWEEN DATEADD(DAY, -60, GETDATE()) AND GETDATE()
GROUP BY EXTRAMAG.PRS_LUNGHEZZA
)t
Related
I'm trying to update the supplier lead time in a table by calculating the difference between date of order and stock receipt date....
UPDATE cr_accs
SET cr_accs.leadtime = Avg(Datediff(day, purchord_hdr.orderdate,
stock_trans.transdate))
FROM stock_items
INNER JOIN stock_trans
ON stock_trans.stockcode = stock_items.stockcode
INNER JOIN purchord_hdr
ON purchord_hdr.seqno = stock_trans.ref1
WHERE cr_accs.accno = purchord_hdr.accno
AND stock_trans.location = 1
AND stock_trans.ref2 = 'RECEIPT'
AND purchord_hdr.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()),-730)
AND stock_items.isactive = 'Y'
AND stock_items.bincode NOT IN ( 'OIO', 'CON' )
However I'm getting an error
An aggregate may not appear in the set list of an UPDATE statement
I've seen other solutions where you would change the query to:
UPDATE cr_accs
SET cr_accs.leadtime = h.calc_lead_time
FROM (SELECT AVG(DATEDIFF(day, purchord_hdr.orderdate, stock_trans.transdate)) AS calc_lead_time
FROM stock_items
INNER JOIN stock_trans
ON stock_trans.stockcode = stock_items.stockcode
INNER JOIN purchord_hdr
ON purchord_hdr.seqno = stock_trans.ref1
INNER JOIN cr_accs
ON cr_accs.accno = purchord_hdr.accno
WHERE cr_accs.accno = purchord_hdr.accno
AND stock_trans.location = 1
AND stock_trans.ref2 = 'RECEIPT'
AND purchord_hdr.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()),-730)
AND stock_items.isactive = 'Y'
AND stock_items.bincode NOT IN ( 'OIO', 'CON' ) ) h
However this is not the solution for me as it doesn't define that the lead time is unique to each supplier...
It may be helpful to point out that each supplier is identified by cr_accs.accno
Any ideas please?
You can also do what you want using a correlated subquery, which might be what you were trying to do:
UPDATE cr_accs
SET cr_accs.leadtime =
(SELECT AVG(DATEDIFF(day, p.orderdate, st.transdate)) AS calc_lead_time
FROM stock_items si JOIN
stock_trans st
ON st.stockcode = si.stockcode JOIN
purchord_hdr p
ON p.seqno = st.ref1
WHERE cr_accs.accno = p.accno AND
st.location = 1 AND
st.ref2 = 'RECEIPT' AND
p.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()), -730) AND
si.isactive = 'Y' AND
si.bincode NOT IN ( 'OIO', 'CON' )
);
I introduced table aliases so the query is easier to write and to read.
SQL Server also gives you the ability to express this using APPLY:
UPDATE a
SET a.leadtime = p.calc_lead_time
FROM cr_accs a CROSS APPLY
(SELECT AVG(DATEDIFF(day, p.orderdate, st.transdate)) AS calc_lead_time
FROM stock_items si JOIN
stock_trans st
ON st.stockcode = si.stockcode JOIN
purchord_hdr p
ON p.seqno = st.ref1
WHERE a.accno = p.accno AND
st.location = 1 AND
st.ref2 = 'RECEIPT' AND
p.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()), -730) AND
si.isactive = 'Y' AND
si.bincode NOT IN ( 'OIO', 'CON' )
) p;
Try this join of the table to the query:
UPDATE c
SET c.leadtime = h.calc_lead_time
FROM cr_accs c
INNER JOIN (
SELECT purchord_hdr.accno,
AVG(DATEDIFF(day, purchord_hdr.orderdate, stock_trans.transdate)) AS calc_lead_time
FROM stock_items
INNER JOIN stock_trans ON stock_trans.stockcode = stock_items.stockcode
INNER JOIN purchord_hdr ON purchord_hdr.seqno = stock_trans.ref1
WHERE stock_trans.location = 1
AND stock_trans.ref2 = 'RECEIPT'
AND purchord_hdr.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()),-730)
AND stock_items.isactive = 'Y'
AND stock_items.bincode NOT IN ('OIO', 'CON')
GROUP BY purchord_hdr.accno
) h ON h.accno = c.accno
I assume (by your code and the error message) that you are using SQL Server.
I have a query
SELECT *
FROM Stops
WHERE CustomerID IN (SELECT ID FROM Customers WHERE Active = 1)
AND DriverID IS NOT NULL
AND TripID IN (SELECT ID
FROM Trips
WHERE ManagerID IN (SELECT ID FROM Users WHERE Active = 1)
AND AssignedToID IN (SELECT ID FROM Users WHERE Active = 1)
AND Modified > DATEADD(day, -60, GETDATE()))
I tried to convert to Join but I am stuck
SELECT *
FROM Stops S
JOIN Customers C ON C.ID = S.CustomerID
JOIN Trips T ON S.TripID = T.ID
WHERE C.ACTIVE = 1
AND S.DriverID IS NOT NULL
AND T.Modified > DATEADD(day, -60, GETDATE())
Using all joins, no nested queries
SELECT * FROM Stops A
INNER JOIN Customers B ON A.CustomerID = B.ID
INNER JOIN Trips C ON A.TripID = C.ID
INNER JOIN Users D ON C.ManagerID = D.ID
INNER JOIN Users E ON C.AssignedToID = E.ID
WHERE A.DriverID IS NOT NULL AND
B.Active = 1 AND
D.Active = 1 AND
E.Active = 1 AND
C.Modified > DATEADD(day, -60, GETDATE());
If you want unique data of stops you can also add "DISTINCT" to the select.
you can try like below subquery and join
SELECT S.* FROM Stops S
JOIN Customers C ON C.ID=S.CustomerID
join (SELECT ID FROM Trips where
ManagerID IN (SELECT ID FROM Users WHERE Active = 1) AND
AssignedToID IN (SELECT ID FROM Users WHERE Active = 1) AND
Modified > DATEADD(day, -60, GETDATE())
) t on S.TripID=t.ID
I'm trying your second code on my end until I came up on the below code. You might try
SELECT *
FROM Stops S
JOIN Customers C ON C.ID = S.CustomerID AND C.ACTIVE = 1
JOIN Trips T ON S.TripID = T.ID AND T.Modified > DATEADD(day, -60, GETDATE())
LEFT JOIN Users U ON T.ManagerID = U.ID AND T.AssignedToID = U.ID
WHERE S.DriverID IS NOT NULL
What I usually do is to draw squares as tables and link them based on the requirements.
Though, still not sure if my answer would work since I have no idea with what you are trying to achieve on your code aside from using JOIN.
I currently have an SQL query that is used to create a matter report for our firms. The problem with it at the moment is that it creates six columns for client/party details which could be reduced to three columns to minimise confusion for the secretaries that will review before the report is used in marketing.
There's three client types - individual, joint party or organisation.
The six columns in the report are ClientFirstName, ClientLastName, ClientEmail (which are all populated if the ClientType is Individual) and PartyFirstName, PartyLastName, PartyEmail (which are all populated if the ClientType is Joint Part or Organisation - sometimes multiple results for each party member).
Here's the query:
SELECT DISTINCT
-- setup columns
[cases].[reference] as MatterNumber,
[dd_entity_d2].[type] as ClientType,
[dd_client].[clientname] as MatterName,
etClient.FirstName as ClientFirstName,
etClient.LastName as ClientLastName,
[dd_entity_d2].[email] as ClientEmail,
[dd_entity_d4].[firstname] as PartyFirstName,
[dd_entity_d4].[lastname] as PartyLastName,
[dd_entity_d4].[email] as PartyEmail,
etActing.[PreferredName] ActingPerson,
[cases].[category] as MatterType,
mt.CreatedOn as MatterOpened,
case mt.[Status]
when 0 then 'In Progress'
When 1 then 'On Hold'
when 2 then 'Completed'
when 3 then 'Not Proceeding'
else 'Unknown' end as MatterStatus
-- mt.LastUpdatedOn as LastModified,
-- end columns
-- setup data
FROM PracticeEvolve_doc.dbo.[cases]
INNER JOIN PracticeEvolve_c1.dbo.DocumaticsMap dm on dm.DocumaticsID = [cases].ID and dm.Entitytype = 'Matter'
INNER JOIN PracticeEvolve_c1.dbo.[Matter] mt on mt.Matterid = dm.ClickOneID
INNER JOIN PracticeEvolve_c1.dbo.[Client] cl on mt.ClientID = cl.ClientID
INNER JOIN PracticeEvolve_c1.dbo.[Entity] etClient on cl.EntityID = etClient.EntityID
LEFT JOIN PracticeEvolve_c1.dbo.EmployeeMatter emActing on emActing.MatterID = mt.MatterID and emActing.AssociationTypeID = 15
LEFT JOIN PracticeEvolve_c1.dbo.Employee eActing on eActing.EmployeeID = emActing.EmployeeID
LEFT JOIN PracticeEvolve_c1.dbo.Entity etActing on etActing.EntityID = eActing.EntityID
LEFT JOIN PracticeEvolve_doc.dbo.[dd_client] ON [dd_client].[id]=[cases].[clientid]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_manytomany] AS [dd_manytomanydd_entity_d2] ON [dd_manytomanydd_entity_d2].[fkid] = [dd_client].[fk_entities]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_entity] as [dd_entity_d2] ON [dd_entity_d2].[id] = [dd_manytomanydd_entity_d2].[pkid]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_manytomany] AS [dd_manytomanydd_party_d3] ON [dd_manytomanydd_party_d3].[fkid] = [dd_entity_d2].[fk_parties]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_party] as [dd_party_d3] ON [dd_party_d3].[id] = [dd_manytomanydd_party_d3].[pkid]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_manytomany] AS [dd_manytomanydd_entity_d4] ON [dd_manytomanydd_entity_d4].[fkid] = [dd_party_d3].[fk_entity]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_entity] as [dd_entity_d4] ON [dd_entity_d4].[id] = [dd_manytomanydd_entity_d4].[pkid]
-- end data
-- setup filters
WHERE [cases].[deleted]=0
AND DATEPART(m, mt.CreatedOn) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, mt.CreatedOn) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
-- AND mt.CreatedOn >= '2017-05-16'
-- AND [dd_entity_d2].[type] = 'Individual'
-- AND mt.LastUpdatedOn >= '2017-04-02'
-- AND mt.[status] = 0
-- end filters and query
What I'd like to do is have it just use the columns FirstName, LastName and Email so that it is populated with the individual's details if the ClientType is individual, or populated with the joint party's/organisation's details if the ClientType is something other than Individual.
Is this possible?
(as a bit of a disclaimer - I'm a novice with database queries, so may not know how to implement a specific statement or string)
You can use Case Statement. I assumed Client type is stored as text but you can change 'individual' to appropriate value.
SELECT DISTINCT
-- setup columns
[cases].[reference] as MatterNumber,
[dd_entity_d2].[type] as ClientType,
[dd_client].[clientname] as MatterName,
CASE WHEN [dd_entity_d2].[type] ='Individual' THEN etClient.FirstName ELSE [dd_entity_d4].[firstname] END AS FirstName,
CASE WHEN [dd_entity_d2].[type] ='Individual' THEN etClient.LastName ELSE [dd_entity_d4].[lastname] END AS LastName,
CASE WHEN [dd_entity_d2].[type] ='Individual' THEN [dd_entity_d2].[email] ELSE [dd_entity_d4].[email] END AS Email,
etActing.[PreferredName] ActingPerson,
[cases].[category] as MatterType,
mt.CreatedOn as MatterOpened,
case mt.[Status]
when 0 then 'In Progress'
When 1 then 'On Hold'
when 2 then 'Completed'
when 3 then 'Not Proceeding'
else 'Unknown' end as MatterStatus
-- mt.LastUpdatedOn as LastModified,
-- end columns
-- setup data
FROM PracticeEvolve_doc.dbo.[cases]
INNER JOIN PracticeEvolve_c1.dbo.DocumaticsMap dm on dm.DocumaticsID = [cases].ID and dm.Entitytype = 'Matter'
INNER JOIN PracticeEvolve_c1.dbo.[Matter] mt on mt.Matterid = dm.ClickOneID
INNER JOIN PracticeEvolve_c1.dbo.[Client] cl on mt.ClientID = cl.ClientID
INNER JOIN PracticeEvolve_c1.dbo.[Entity] etClient on cl.EntityID = etClient.EntityID
LEFT JOIN PracticeEvolve_c1.dbo.EmployeeMatter emActing on emActing.MatterID = mt.MatterID and emActing.AssociationTypeID = 15
LEFT JOIN PracticeEvolve_c1.dbo.Employee eActing on eActing.EmployeeID = emActing.EmployeeID
LEFT JOIN PracticeEvolve_c1.dbo.Entity etActing on etActing.EntityID = eActing.EntityID
LEFT JOIN PracticeEvolve_doc.dbo.[dd_client] ON [dd_client].[id]=[cases].[clientid]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_manytomany] AS [dd_manytomanydd_entity_d2] ON [dd_manytomanydd_entity_d2].[fkid] = [dd_client].[fk_entities]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_entity] as [dd_entity_d2] ON [dd_entity_d2].[id] = [dd_manytomanydd_entity_d2].[pkid]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_manytomany] AS [dd_manytomanydd_party_d3] ON [dd_manytomanydd_party_d3].[fkid] = [dd_entity_d2].[fk_parties]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_party] as [dd_party_d3] ON [dd_party_d3].[id] = [dd_manytomanydd_party_d3].[pkid]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_manytomany] AS [dd_manytomanydd_entity_d4] ON [dd_manytomanydd_entity_d4].[fkid] = [dd_party_d3].[fk_entity]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_entity] as [dd_entity_d4] ON [dd_entity_d4].[id] = [dd_manytomanydd_entity_d4].[pkid]
-- end data
-- setup filters
WHERE [cases].[deleted]=0
AND DATEPART(m, mt.CreatedOn) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, mt.CreatedOn) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
-- AND mt.CreatedOn >= '2017-05-16'
-- AND [dd_entity_d2].[type] = 'Individual'
-- AND mt.LastUpdatedOn >= '2017-04-02'
-- AND mt.[status] = 0
-- end filters and query
SELECT
P.P_DESC AS P,
D.PD_NAME AS D,
D.GPE_NBR AS GPE,
D.GPE_GEN_NM,
D.GPE_2_ ,
D.GPE_4c ,
SUBSTR (TRIM(C.FILL_DATE__ID),1,6),
C.fill_Date__ID,
Prod.PD_DESC ,
DMC.M_A_NBR,
DMC.MAD_NBR ,
DMC.FT_NAME,
DMC.LA_NAME,
DDB.DATE_DATE,
CAST((CURRENT_DATE - DDB.DATE_DATE)/365.25 as Int) M_AGE_TODAY,
RXDOC.PB_FT_NAME || ' ' || RXDOC.PB_LA_NAME ,
RXDOC.PB_ID,
DT.D_TYPE_DESC ,
CASE WHEN SDL.GEPE IS NOT NULL THEN 'Y' ELSE 'N' END AS FLAG,
COUNT (C.PHR_C_ID) AS CCount,
SUM (C.AMT_PAID) AS Spend
FROM O_PHAR_C C
INNER JOIN _D D ON C.D__ID=D.D__ID
INNER JOIN _P P
ON C.P__ID = P.P__ID
AND C.P__ID = 00001
INNER JOIN _M_CURR DMC ON C.PB_M_CURR_ID = DMC.M_CURR_ID
INNER JOIN _M DM ON DM.M__ID = DMC.M__ID
INNER JOIN _DATE DDB ON DDB.DATE__ID = DM.BIRTH_DATE__ID
INNER JOIN _M_ELIG_CURR DMEC ON C.PB_M_ELIG_CURR_ID = DMEC.M_ELIG_CURR_ID
LEFT OUTER JOIN BA_PROD_LAB_OWN.specialtyDList SDL
ON D.GPE_NBR = SDL.GPE
AND SDL.EFF_END_DATE >= CURRENT_DATE
LEFT OUTER JOIN _PD Prod ON DMEC.PD__ID = Prod.PD__ID
LEFT OUTER JOIN _RX_PB RXDOC ON C.PB__ID=RXDOC.PB__ID
LEFT OUTER JOIN _PHAR_D_TYPE DT ON C.PHAR_D_TYPE__ID = DT.PHAR_D_TYPE__ID
WHERE C.fill_date__ID BETWEEN 20170201 AND 20170228
AND C.RE_I = 'N'
AND C.sR__ID IN (96,13,203)
GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14, 15, 16, 17, 18, 19
HAVING COUNT(*) >= 10;
I want to use this query to return instances of the C.PHR_C_ID that are more than or equal to 10. However, when I limit my select statement to that column I get the desired result but when I add all these columns to it 'having count' returns 0. There are more than zero records; I think there is something wrong with the query.
The problem is that when you add in your fields and GROUP BY them, you get a count of records for that distinct list of fields. You can probably switch to a QUALIFY statement instead. This will sum up the results by distinct C.PHR_C_ID ignoring the other fields, and then return any fields for that distinct C.PHR_C_ID which has a count(*) >= 10.
SELECT
P.P_DESC AS P,
D.PD_NAME AS D,
D.GPE_NBR AS GPE,
D.GPE_GEN_NM,
D.GPE_2_ ,
D.GPE_4c ,
SUBSTR (TRIM(C.FILL_DATE__ID),1,6),
C.fill_Date__ID,
Prod.PD_DESC ,
DMC.M_A_NBR,
DMC.MAD_NBR ,
DMC.FT_NAME,
DMC.LA_NAME,
DDB.DATE_DATE,
CAST((CURRENT_DATE - DDB.DATE_DATE)/365.25 as Int) M_AGE_TODAY,
RXDOC.PB_FT_NAME || ' ' || RXDOC.PB_LA_NAME ,
RXDOC.PB_ID,
DT.D_TYPE_DESC ,
CASE
WHEN SDL.GEPE IS NOT NULL THEN 'Y'
ELSE 'N'
END AS FLAG,
COUNT(*) OVER (PARTITION BY C.PHR_C_ID) AS CCount,
C.AMT_PAID AS Spend
FROM O_PHAR_C C
INNER JOIN _D D
ON C.D__ID=D.D__ID
INNER JOIN _P P
ON C.P__ID = P.P__ID
AND C.P__ID = 00001
INNER JOIN _M_CURR DMC
ON C.PB_M_CURR_ID = DMC.M_CURR_ID
INNER JOIN _M DM
ON DM.M__ID = DMC.M__ID
INNER JOIN _DATE DDB
ON DDB.DATE__ID = DM.BIRTH_DATE__ID
INNER JOIN _M_ELIG_CURR DMEC
ON C.PB_M_ELIG_CURR_ID = DMEC.M_ELIG_CURR_ID
LEFT OUTER JOIN BA_PROD_LAB_OWN.specialtyDList SDL
ON D.GPE_NBR = SDL.GPE
AND SDL.EFF_END_DATE >= CURRENT_DATE
LEFT OUTER JOIN _PD Prod
ON DMEC.PD__ID = Prod.PD__ID
LEFT OUTER JOIN _RX_PB RXDOC
ON C.PB__ID=RXDOC.PB__ID
LEFT OUTER JOIN _PHAR_D_TYPE DT
ON C.PHAR_D_TYPE__ID = DT.PHAR_D_TYPE__ID
WHERE
C.fill_date__ID BETWEEN 20170201 AND 20170228
AND C.RE_I = 'N'
AND C.sR__ID IN (96,13,203)
QUALIFY COUNT(*) OVER (PARTITION BY C.PHR_C_ID) >= 10;
I'm using the following SQL query:
select
FilteredSystemUser.systemuserid,
FilteredPhoneCall.regardingobjectid
from
FilteredPhoneCall
Inner Join
FilteredSystemUser on FilteredSystemUser.systemuserid in (FilteredPhoneCall.createdby)
Inner Join
FilteredLead on FilteredLead.leadid = FilteredPhoneCall.regardingobjectid
where
DateDiff(d, FilteredPhoneCall.createdon, GETDATE()) = 0
and FilteredLead.statecode = 0
and FilteredLead.ownerid = FilteredSystemUser.systemuserid
and FilteredPhoneCall.statecode = '1'
and FilteredPhoneCall.regardingobjecttypecode = 4
and FilteredPhoneCall.createdby in ('c2dd1ddc-0374-e611-80dc-00155d3d1992', '53cfbe3a-a09a-e611-80df-00155dce24d0')
and get the following output
Here I have two entries in regardingid 97C29D24-BEE2-E611-80F1-00155DCE24EF,091B1CAB-C2E2-E611-80F1-00155DCE24EF against same system user.so i need to consider this as single entry and get the count other than this the both system users having another two ids.
I expect the above output
To get count of distinct values of a column reference here...
SQL: Count distinct values from one column based on multiple criteria in other columns
For your case, try this:
select
FilteredSystemUser.systemuserid,
Count(DISTINCT FilteredPhoneCall.regardingobjectid ) as NoofCall
from
FilteredPhoneCall
Inner Join
FilteredSystemUser on FilteredSystemUser.systemuserid in (FilteredPhoneCall.createdby)
Inner Join
FilteredLead on FilteredLead.leadid = FilteredPhoneCall.regardingobjectid
where
DateDiff(d, FilteredPhoneCall.createdon, GETDATE()) = 0
and FilteredLead.statecode = 0
and FilteredLead.ownerid = FilteredSystemUser.systemuserid
and FilteredPhoneCall.statecode = '1'
and FilteredPhoneCall.regardingobjecttypecode = 4
and FilteredPhoneCall.createdby in ('c2dd1ddc-0374-e611-80dc-00155d3d1992', '53cfbe3a-a09a-e611-80df-00155dce24d0')
Group by FilteredSystemUser.systemuserid
TRY THIS
;with CTE
AS (
select
FilteredSystemUser.systemuserid,
FilteredPhoneCall.regardingobjectid
from
FilteredPhoneCall
Inner Join
FilteredSystemUser on FilteredSystemUser.systemuserid in (FilteredPhoneCall.createdby)
Inner Join
FilteredLead on FilteredLead.leadid = FilteredPhoneCall.regardingobjectid
where
DateDiff(d, FilteredPhoneCall.createdon, GETDATE()) = 0
and FilteredLead.statecode = 0
and FilteredLead.ownerid = FilteredSystemUser.systemuserid
and FilteredPhoneCall.statecode = '1'
and FilteredPhoneCall.regardingobjecttypecode = 4
and FilteredPhoneCall.createdby in ('c2dd1ddc-0374-e611-80dc-00155d3d1992', '53cfbe3a-a09a-e611-80df-00155dce24d0') )
select count(CTE.systemuserid) as myCOUNT,CTE.systemuserid,CTE.regardingobjectid from CTE
group by CTE.systemuserid,CTE.regardingobjectid
You can use count() and group by to achive this.
select COUNT(DISTINCT FilteredPhoneCall.regardingobjectid ) as NoofCall
,FilteredSystemUser.systemuserid
from FilteredPhoneCall
inner Join FilteredSystemUser
on FilteredSystemUser.systemuserid in(FilteredPhoneCall.createdby)
Join FilteredLead
on FilteredLead.leadid = FilteredPhoneCall.regardingobjectid
where DateDiff(d, FilteredPhoneCall.createdon, GETDATE()) = 0
and FilteredLead.statecode = 0 and FilteredLead.ownerid = FilteredSystemUser.systemuserid
and FilteredPhoneCall.statecode = '1' and FilteredPhoneCall.regardingobjecttypecode = 4
and FilteredPhoneCall.createdby in ('c2dd1ddc-0374-e611-80dc-00155d3d1992','53cfbe3a-a09a-e611-80df-00155dce24d0')
and FilteredSystemUser.systemuserid in ('c2dd1ddc-0374-e611-80dc-00155d3d1992','53cfbe3a-a09a-e611-80df-00155dce24d0')
GROUP BY FilteredSystemUser.systemuserid