How can I structure the below query to run through multiple databases all at the same time.
To calculate the total number of active users in the db, I currently have to run the query one database at a time.
Is there some kind of foreach function I can run dynamically?
with data as
(select p.CoNum CoNum, p.LastName, p.Name,co.name Company, liGender.Description as Gender, liEth.Description as EthnicGroup,Isnull(Limed.Description,'Not Specified') FinancialAid,
vwPTU.[UserP Type] as UserPType
from UsersP p
left outer join ListItem liGender on liGender.Id = p.Gender
left outer join ListItem liEth on liEth.Id = p.EthnicGroup
left outer join ListItem limed on limed.Id = p.FinancialAidId
inner join UserPOrgNodeAssociation pona on P.Id = pona.UserPId
inner join CoAssociation coda on pona.CoNodeDescAssociationId = coda.Id
inner join Company co on coda.companyid=co.id
left outer join [dbo].[vw_XUserUniqueView] vwPTU on p.Id = vwPTU.Id
and vwPTU.[ValidToDate] > '2015/12/31 23:59 PM'
where vwPTU.[User Type] is not null
)
select Company, count(distinct CoNum) as Total
from data
group by company
Try using SP_MSForEachDB procedure..
exec sp_msforeachdb 'Your Query here'
Related
Im still improving my query writing skills and i have little problem with select which uses stastical function like average max etc. Firstly i wrote simple query based on single table and it works perfect:
select e.Article, avg(e.Price) as 'Average', max(e.Price) as 'Max', min(e.Price) as 'Min' from pub.E_ArtPrice e
group by e.Article
order by e.Article
Next step was to create something little more complicated to get information which is really useful for me:
Select m.Part, m.Quantity, m.OnHand, m.postingdate, m.storagearea, p.MEM_PostingCode_ID, koss.Description, ko.Carrier, avg(e.price) as 'Average', max(e.price) as 'Max', min(e.price) as 'Min'
from pub.MLL_Movements m inner join pub.MEM_PostingCode p on (m.MEM_PostingCode_Obj = p.MEM_PostingCode_Obj)
left outer join pub.s_Carrier ko on (m.CostAccObject_Obj = ko.S_Carrier_Obj)
left outer join pub.s_CostCentre kos on (m.CostAccObject_Obj = kos.S_CostCentre_Obj)
left outer join pub.S_CostCentreSpr koss on (kos.CostCentre = koss.CostCentre)
left outer join pub.E_ArtPrice e on (m.Part = e.Article)
where p.MEM_PostingCode_ID = 'AUKJ'
I didn't put the group by clause here because after many tries it didnt work.
enter image description here
All your select columns other than the aggregate columns should be in your group by clause hence try the below
Select m.Part, m.Quantity, m.OnHand, m.postingdate, m.storagearea, p.MEM_PostingCode_ID, koss.Description, ko.Carrier, avg(e.price) as 'Average', max(e.price) as 'Max', min(e.price) as 'Min'
from pub.MLL_Movements m inner join pub.MEM_PostingCode p on (m.MEM_PostingCode_Obj = p.MEM_PostingCode_Obj)
left outer join pub.s_Carrier ko on (m.CostAccObject_Obj = ko.S_Carrier_Obj)
left outer join pub.s_CostCentre kos on (m.CostAccObject_Obj = kos.S_CostCentre_Obj)
left outer join pub.S_CostCentreSpr koss on (kos.CostCentre = koss.CostCentre)
left outer join pub.E_ArtPrice e on (m.Part = e.Article)
where p.MEM_PostingCode_ID = 'AUKJ'
group by m.Part, m.Quantity, m.OnHand, m.postingdate, m.storagearea, p.MEM_PostingCode_ID, koss.Description, ko.Carrier
Goal:
I wish to get the Count of how many times a WorkItem was re-assigned
From what I understand the proper query is the following:
SELECT
WorkItemDimvw.Id,
COUNT(WorkItemAssignedToUserFactvw.WorkItemAssignedToUser_UserDimKey) AS Assignments
FROM WorkItemDimvw INNER JOIN WorkItemAssignedToUserFactvw
ON WorkItemDimvw.WorkItemDimKey = WorkItemAssignedToUserFactvw.WorkItemDimKey
GROUP BY WorkItemDimvw.Id
The EXISTING query is below and I'm wondering / forgeting if I should:
Just add in COUNT(WorkItemAssignedToUserFactvw.WorkItemAssignedToUser_UserDimKey) AS Assignments since joins are existing, except it is group by WorkItemDimvw.Id
Should it instead be a subquery in the Select below?
Query:
SELECT
SRD.ID,
SRD.Title,
SRD.Description,
SRD.EntityDimKey,
WI.WorkItemDimKey,
IATUFact.DateKey
FROM
SLAConfigurationDimvw
INNER JOIN SLAInstanceInformationFactvw
ON SLAConfigurationDimvw.SLAConfigurationDimKey = SLAInstanceInformationFactvw.SLAConfigurationDimKey
RIGHT OUTER JOIN ServiceRequestDimvw AS SRD
INNER JOIN WorkItemDimvw AS WI
ON SRD.EntityDimKey = WI.EntityDimKey
LEFT OUTER JOIN WorkItemAssignedToUserFactvw AS IATUFact
ON WI.WorkItemDimKey = IATUFact.WorkItemDimKey
AND IATUFact.DeletedDate IS NULL
The trick is to aggregate the data on a sub query, before you join it.
SELECT
SRD.ID,
SRD.Title,
SRD.Description,
SRD.EntityDimKey,
WI.WorkItemDimKey,
IATUFact.DateKey,
IATUFact.Assignments
FROM
SLAConfigurationDimvw
INNER JOIN
SLAInstanceInformationFactvw
ON SLAConfigurationDimvw.SLAConfigurationDimKey = SLAInstanceInformationFactvw.SLAConfigurationDimKey
RIGHT OUTER JOIN
ServiceRequestDimvw AS SRD
ON <you're missing something here>
INNER JOIN
WorkItemDimvw AS WI
ON SRD.EntityDimKey = WI.EntityDimKey
LEFT OUTER JOIN
(
SELECT
WorkItemDimKey,
DateKey,
COUNT(WorkItemAssignedToUser_UserDimKey) AS Assignments
FROM
WorkItemAssignedToUserFactvw
WHERE
DeletedDate IS NULL
GROUP BY
WorkItemDimKey,
DateKey
)
IATUFact
ON WI.WorkItemDimKey = IATUFact.WorkItemDimKey
I have the following query running in a report with a picklist of 4 seperate Databases. It is running fine, but I need to exclude all transactions in one of the databases, before a certain period.
How can I add to this query, that will allow this, say I have DBa, DBb, DBc and DBd - and I want all transactions before period 35 on DBa to be ignored, but still include this info for the remaining 3 DB?
SELECT 'Actual'[Type],
RTRIM(Entities.Name) AS 'CompanyName',
gl.accountlink,
gl.Master_Sub_Account, (sum(debit)-sum(credit))[Opening Balance]
FROM _bvgltransactionsfull glt
INNER JOIN _evGLAccountsFull gl ON glt.AccountLink = gl.AccountLink
INNER JOIN _etblperiod p ON p.idperiod = glt.period
LEFT JOIN [Entities] ON 1=1
WHERE glt.period < #PeriodStart#
AND isBSAccountType = 1
GROUP BY Entities.Name,
gl.accountlink,
master_sub_account
UNION ALL
SELECT 'Opening',
RTRIM(Entities.Name),
accountlink,
Master_Sub_Account,
AccumActual
FROM _evGLAccountsAnnualOpeningBalances
LEFT JOIN [Entities] ON 1=1
DB_NAME() will return the current connected database name. You could apply a filter on DB_NAME() on your query, assuming that you change your current connection before issuing each query:
SELECT
'Actual'[Type],
RTRIM(Entities.Name) AS 'CompanyName',
gl.accountlink,
gl.Master_Sub_Account,
(sum(debit)-sum(credit))[Opening Balance]
FROM
_bvgltransactionsfull glt
INNER JOIN _evGLAccountsFull gl ON glt.AccountLink = gl.AccountLink
INNER JOIN _etblperiod p ON p.idperiod = glt.period
LEFT JOIN [Entities] ON 1=1
WHERE
glt.period < #PeriodStart#
AND isBSAccountType = 1
AND
(
DB_NAME() <> 'DBa' OR
(DB_NAME() = 'DBa' AND /*Transactions after period 35*/)
)
I am trying run a query to include all records. it is omitting records if one of the fields is null. Changing the "output all fields" in query properties to Yes brings in all fields but that is not what i need. i need all records. Here is my SQL query:
SELECT tblBOOK.Concat, tblBOOK.Owner1, tblBOOK.Owner2,
tblIndustry.[Industry Name], tblOwner1.Points, tblOwner2.Points,
tblIndustry.[Industry Points], tblBOOK.FILE, tblBOOK.SCORE,
tblFILE.Points, tblSCORE.Points, tblBOOK.Risk, tblRisk.Points,
[tblOwner1]![Points]+[tblOwner2]![Points]+[Industry Points]+
[tblFILE]! [Points]+[tblSCORE]![Points]+[tblRisk]![Points]
AS TtlPoints
FROM tblRisk
INNER JOIN (tblSCORE
INNER JOIN (tblFILE
INNER JOIN ((tblOwner1
INNER JOIN (tblOwner2
INNER JOIN tblBOOK
ON (tblOwner2.Secondary = tblBOOK.Owner2)
AND (tblOwner2.Primary = tblBOOK.Owner1))
ON tblOwner1.Primary = tblOwner2.Primary)
INNER JOIN tblIndustry
ON tblBOOK.Industry = tblIndustry.[Industry Name])
ON tblFILE.Score = tblBOOK.FILE)
ON tblSCORE.Score = tblBOOK.SCORE)
ON tblRisk.Factor = tblBOOK.Risk;
I also tried to add "IsNull" to the criteria and then in returns no records.
I needed to change these from INNER JOINS to LEFT JOINS
SELECT tblBOOK.Concat, tblIndustry.[Industry Name],tblIndustry.[Industry Points],
tblOwner1.Primary, tblOwner1.Points, tblFILE.Score, tblFILE.Points, tblCARD.Score,
tblCARD.Points, tblRisk.Factor, tblRisk.Points,
[Industry Points]+[tblOwner1]![Points]+[tblFILE]![Points]+[tblCARD]![Points]+
[tblRisk]![Points]
AS TotalPoints
FROM ((((tblBOOK
LEFT JOIN tblIndustry ON tblBOOK.Industry = tblIndustry.[Industry Name])
LEFT JOIN tblOwner1 ON tblBOOK.Owner1 = tblOwner1.Primary)
LEFT JOIN tblFILE ON tblBOOK.CSS = tblFILE.Score)
LEFT JOIN tblCARD ON tblBOOK.CARD = tblCARD.Score)
LEFT JOIN tblRisk ON tblBOOK.Risk = tblRisk.Factor;
I have 3 tables:
CP_carthead (idOrder)
CP_cartrows (idOrder, idCartRow)
CP_shipping (idCartRow, idShipping, dateShipped)
There can be multiple idCartRows per idOrder.
I want to get all orders where all its idCartRows exist in CP_shipping. This seems like it should be simple, but I haven't found much on the web.
Here's my query now:
SELECT
s.idOrder
, s.LatestDateShipped
FROM
CP_carthead o
LEFT OUTER JOIN (
SELECT
MAX(s.dateShipped) [LatestDateShipped]
, r.idOrder
FROM
CP_shipping s
LEFT OUTER JOIN CP_cartrows r ON s.idCartRow = r.idCartRow
GROUP BY
r.idOrder
) s ON o.idOrder = s.idOrder
Your query is returning rows from "s" and not the orders. Based on your question, I came up with this query:
select o.*
from CP_Carthead o
where o.orderId in (select cr.idOrder
from cp_cartrows cr left outer join
cp_shipping s
on cr.idCartRow = s.IdCartrow
group by cr.idOrder
having count(s.idCartRow) = COUNT(*)
)
The subquery in the in statement is getting orders all of whose cartrows are in shipping.