试图结合这两个查询

时间:2014-05-15 15:03:38

标签: sql-server

我正在努力将这两个简单的查询结合起来(我对SQL和所有内容都很新)。我已经尝试了很多方法来组合它们(总结情况......然后1其他0)并使用连接并尝试实现Exist但仍然给我一个错误。

无论如何,我想要合并的两个查询如下:

Select
Count (*) as TotalA,
z.zname
From CTable c, STable s, SLTable sl, ZTable z
Where c.ID=s.sID
and s.sID=sl.ID
and sl.zID=z.zID
Group by z.zname
Order by z.zname

Select 
Count (*) as TotalB,
z.zname
From STable s, SLTable sl, ZTable z
Where s.sID=sl.sID
and sl.zID=z.zID
Group By z.zName
Order By z.zName

以下是我尝试获取信息的尝试之一

Select 
Count (*) as TotalB,
sum (case when sl.sID=s.sID and sl.zID=z.zID then 1 else 0 end) as  TotalA,
z.zname
From STable s, SLTable sl, ZTable z, CTable c
Where s.sID=sl.sID
and sl.zID=z.zID
and c.sID=s.sID
Group By z.zname
Order By z.zname

这几乎给了我三个总A,总B和Z的列 - 但总A和总B彼此完全相同 - 从第一个查询中获取所有正确的信息,然后将其复制到Total B区。

我确信我只是粗暴地试图将它们粉碎在一起,但我真的不知道如何将它们合并。

感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

以下内容如何:

SELECT COUNT(*) AS TotalA, 
(
  SELECT COUNT(*) as TotalB
  FROM STable ss
    INNER JOIN SLTable sssl ON ss.sID = sssl.sID 
    INNER JOIN ZTable sz ON sssl.zID = sz.zID
  WHERE sz.zname = z.zname 
) AS TotalB, z.zname
FROM CTable c
  INNER JOIN STable s ON c.ID = s.sID
  INNER JOIN SLTable sl ON s.sID = sl.ID 
  INNER JOIN ZTable z ON sl.zID = z.zID
GROUP BY z.zname

答案 1 :(得分:0)

CTE粉碎它们怎么样?

with

TableA as
(Select
Count (*) as TotalA,
z.zname
From CTable c, STable s, SLTable sl, ZTable z
Where c.ID=s.sID
and s.sID=sl.ID
and sl.zID=z.zID
Group by z.zname),

TableB as
(Select 
Count (*) as TotalB,
z.zname
From STable s, SLTable sl, ZTable z
Where s.sID=sl.sID
and sl.zID=z.zID
Group By z.zname)

/* --I've tested with this sample to avoid filling CTable,STable,SLTable,ZTable:
create table TableA(zname varchar(100),TotalA int)
create table TableB(zname varchar(100),TotalB int)
insert TableA(zname,TotalA) select 'a',10 union all select 'b',null
insert TableB(zname,TotalB) select 'a',20 union all select 'c',10 union all select 'd',50
select * from TableA
select * from TableB
*/

select COALESCE(TableA.zname,TableB.zname) as zname,TableA.TotalA,TableB.TotalB
from TableA full join TableB on TableA.zname=TableB.zname

如果您的SQL Server使用CTE已经很老了,只需创建临时表并使用它们。像这样:

Select
    Count (*) as TotalA,
    z.zname
    into #TableA
    From CTable c, STable s, SLTable sl, ZTable z
    Where c.ID=s.sID
    and s.sID=sl.ID
    and sl.zID=z.zID
    Group by z.zname

答案 2 :(得分:0)

以下是我如何回答这个问题 - 通过一些研究 - 以及你们的累积回答:

SELECT
    ts.zname,
    TotalA ,
    TotalB
FROM
(
    Select
    Count (*) as TotalA,
    z.zname
    From CTable c, STable s, SLTable sl, ZTable z
    Where c.sID=s.sID
    and s.sID=sl.sID
    and sl.zID=z.zID
    Group by z.zname
) TC
INNER JOIN 
(
    Select 
    Count (*) as TotalB,
    z.zname
    From STable s, SLTable sl, ZTable z
    Where s.sID=sl.sID
    and sl.zID=z.zID
    Group By z.zname
) ts ON ts.zname = tc.zname
Order By ts.ZoneName