简化SQL查询,减少连接数

时间:2019-06-27 10:22:49

标签: sql sql-server tsql

查询给出正确的结果,但我希望以行数为单位的最佳查询。可以更简化吗?

SELECT 

[EventName]

  FROM [WorldEvents].[dbo].[tblEvent] EVNT
  INNER JOIN
  [WorldEvents].[dbo].[tblCountry] CTRY
  ON
  EVNT.CountryID = CTRY.CountryID
  INNER JOIN
  [WorldEvents].[dbo].[tblContinent] CNT
  ON
  CNT.ContinentID = CTRY.ContinentID
  WHERE [ContinentName] 
   IN
  (
  SELECT CNAME FROM(

            SELECT TOP 3
            [ContinentName] AS CNAME,
            COUNT(EventName) AS EVENT_PER_CONTINENT
            FROM (
            SELECT [ContinentName],
            [EventName]
            --,SUM(COUNT(EventName) OVER(PARTITION BY [ContinentName] ORDER BY [ContinentName] ,[EventName]) AS COUNT

            FROM [WorldEvents].[dbo].[tblContinent] CONTINENT
            INNER JOIN 
            [WorldEvents].[dbo].[tblCountry] COUNTRY
            ON
            CONTINENT.ContinentID = COUNTRY.ContinentID
            INNER JOIN 
            [WorldEvents].[dbo].[tblEvent] EVE
            ON 
            EVE.[CountryID] = COUNTRY.[CountryID]

            ) TABLE1

GROUP BY 
[ContinentName]

ORDER BY EVENT_PER_CONTINENT
ASC
) TABLE2

)

1 个答案:

答案 0 :(得分:1)

如果我正确地遵循逻辑,则您希望按计数来计数来自“前3个”大洲的事件。这是获取此信息的更简单方法:

xquery version "1.0-ml";

let $tde :=
<template xmlns="http://marklogic.com/xdmp/tde">
  <context>/test</context>
  <vars>
    <var>
      <name>subprefix</name>
      <val>"http://www.test.com/resource/test/"</val>
    </var>
    <var>
      <name>objprefix</name>
      <val>"http://www.test.com/resource/test/"</val>
    </var>
  </vars>
  <templates>
    <template>
      <context>FullName</context>
      <triples>
        <triple>
            <subject>
                <val>sem:iri($subprefix || ../ElemenetName)</val>
                <invalid-values>ignore</invalid-values>
            </subject>
            <predicate>
                <val>sem:iri('is')</val>
            </predicate>
            <object>
                <val>sem:iri($objprefix || .)</val>
                <invalid-values>ignore</invalid-values>
            </object>
        </triple>
      </triples>
    </template>
  </templates>
</template>
let $xml1 := <test><ElemenetName>elem</ElemenetName><FullName>full</FullName></test>
let $xml2 := <test><ElemenetName>elem</ElemenetName></test>
let $xml3 := <test><FullName>full</FullName></test>
return tde:node-data-extract(($xml1, $xml2, $xml3), $tde)