简体   繁体   中英

Merge of two select queries

I want to merge these two Select queries into single query. How can i do this?

 SELECT link_id, COUNT(*)  FROM Loc  GROUP BY link_id 

     SELECT Slink.[xlink:Show],Loc.[xlink:show],
     Slink.[xlink:actuate],Loc.[xlink:actuate] ,
     href, Sem.SemRoleDescrip
     FROM Sem  JOIN Loc  ON 
     Sem.SemRoleId = Loc.SemRoleId
  JOIN Slink ON Slink.link_id = Loc.link_id

One solution would be to

  • add the COUNT statement as a subquery
  • (LEFT) JOIN this subselect with the SLink table
  • Add the LinkCount to the list of selected values.

SQL Statement

SELECT  Slink.[xlink:Show]
        , Loc.[xlink:show]
        , Slink.[xlink:actuate]
        , Loc.[xlink:actuate] 
        , href
        , Sem.SemRoleDescrip
        , SLinkCount.LinkCount
FROM    Sem  
        JOIN Loc ON Sem.SemRoleId = Loc.SemRoleId
        JOIN Slink ON Slink.link_id = Loc.link_id
        LEFT JOIN (
          SELECT  link_id, COUNT(*) AS LinkCount 
          FROM    Loc  
          GROUP BY 
                  link_id 
        ) SLinkCount ON SLinkCount.link_id = Slink.link_id                  

You might want to read up on Subqueries in the reference manual

12.2.9.8. Subqueries in the FROM Clause

Subqueries are legal in a SELECT statement's FROM clause. The actual syntax is:

SELECT ... FROM (subquery) [AS] name ...

The [AS] name clause is mandatory, because every table in a FROM clause must have a name. Any columns in the subquery select list must have unique names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM