Statistische functies - aantal
van toepassing op:SQL Server-
Retourneert het aantal items dat is opgenomen in de reeks die is opgegeven door $arg.
Syntaxis
fn:count($arg as item()*) as xs:integer
Argumenten
$arg
Te tellen items.
Opmerkingen
Retourneert 0 als $arg een lege reeks is.
Voorbeelden
Dit onderwerp bevat XQuery-voorbeelden voor XML-exemplaren die zijn opgeslagen in verschillende xml--typekolommen in de AdventureWorks-database.
Een. De functie count() XQuery gebruiken om het aantal werkcentrumlocaties in de productie van een productmodel te tellen
De volgende query telt het aantal werkcentrumlocaties in het productieproces van een productmodel (ProductModelID=7).
SELECT Production.ProductModel.ProductModelID,
Production.ProductModel.Name,
Instructions.query('
declare namespace AWMI="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions";
<NoOfWorkStations>
{ count(/AWMI:root/AWMI:Location) }
</NoOfWorkStations>
') as WorkCtrCount
FROM Production.ProductModel
WHERE Production.ProductModel.ProductModelID=7
Let op het volgende uit de vorige query:
De naamruimte trefwoord in XQuery Prolog- definieert een naamruimtevoorvoegsel. Het voorvoegsel wordt vervolgens gebruikt in de hoofdtekst van XQuery.
De query maakt XML die het <
NoOfWorkStations
> element bevat.De functie count() in de hoofdtekst van XQuery telt het aantal <
Location
> elementen.
Dit is het resultaat:
ProductModelID Name WorkCtrCount
-------------- ---------------------------------------------------
7 HL Touring Frame <NoOfWorkStations>6</NoOfWorkStations>
U kunt ook de XML samenstellen om de productmodel-id en -naam op te nemen, zoals wordt weergegeven in de volgende query:
SELECT Instructions.query('
declare namespace AWMI="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions";
<NoOfWorkStations
ProductModelID= "{ sql:column("Production.ProductModel.ProductModelID") }"
ProductModelName = "{ sql:column("Production.ProductModel.Name") }" >
{ count(/AWMI:root/AWMI:Location) }
</NoOfWorkStations>
') as WorkCtrCount
FROM Production.ProductModel
WHERE Production.ProductModel.ProductModelID= 7
Dit is het resultaat:
<NoOfWorkStations ProductModelID="7"
ProductModelName="HL Touring Frame">6</NoOfWorkStations>
In plaats van XML kunt u deze waarden retourneren als niet-XML-type, zoals wordt weergegeven in de volgende query. De query maakt gebruik van de methode value() (XML-gegevenstype) om het aantal locaties van het werkcentrum op te halen.
SELECT ProductModelID,
Name,
Instructions.value('declare namespace AWMI="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions";
count(/AWMI:root/AWMI:Location)', 'int' ) as WorkCtrCount
FROM Production.ProductModel
WHERE ProductModelID=7
Dit is het resultaat:
ProductModelID Name WorkCtrCount
-------------- ---------------------------------
7 HL Touring Frame 6