SQL多个选择查询到同一个表上的单独列中

时间:2016-06-03 22:30:35

标签: tsql select

对于这样做的方式我看起来很高,而且之前提出的几个问题有相似之处,但没有一个能帮助我做我想做的事。

这就是我所拥有的:

select siteid, count(dmovedin) as dmovedin

from Ledgers

where dDeleted is null and iTferFromLedID is NULL and dmovedin between '2016-05-01 00:00:00' and '2016-05-31 23:23:59'

group by siteid

order by siteid

go

select siteid, count(dMovedOut) as dmovedout

from Ledgers

where dDeleted is null and iTfertoLedID is NULL and dmovedout between '2016-05-01 00:00:00' and '2016-05-31 23:23:59'

group by siteid

order by siteid

目前,SQL返回两个表,每个表都包含一个站点ID列和一个唯一列。

我想要做的是在同一张桌子中并排放置这两个独特的列,但我无法弄清楚如何做到这一点。

有没有人有任何想法?

2 个答案:

答案 0 :(得分:0)

看起来一切都是相同的,但是选择中的第二列。

在这种情况下,将它们组合在一起:

select siteid, count(dmovedin) as dmovedin, count(dmovedout) as dmovedout

然后将你的Where:

组合起来
where dDeleted is null 
and (iTfertoLedID is NULL 
 and iTferFromLedID is NULL)
and (dmovedin between '2016-05-01 00:00:00' and '2016-05-31 23:23:59'
**and** dmovedout between '2016-05-01 00:00:00' and '2016-05-31 23:23:59')

根据您想要的逻辑,粗体'和'可能是'或'(这就是我在括号中嵌套这些行的原因)。我不知道你要做什么,所以我不能肯定地说。

其他一切都应该是一样的。你试过吗?这似乎是基本的SQL。

答案 1 :(得分:0)

如果您将每个计数查询转换为查询中的“表格”,该怎么办?由于你有不同的where子句,我认为它会更容易。

SELECT A.siteid, A.dmovedin, ISNULL(B.dmovedout, 0) dmovedout
FROM
(
     select siteid, count(dmovedin) as dmovedin
     from Ledgers
     where dDeleted is null and iTferFromLedID is NULL and dmovedin between '2016-05-01 00:00:00' and '2016-05-31 23:23:59'
     group by siteid
     order by siteid
) A 
LEFT JOIN (
     select siteid, count(dMovedOut) as dmovedout
     from Ledgers
     where dDeleted is null and iTfertoLedID is NULL and dmovedout between '2016-05-01 00:00:00' and '2016-05-31 23:23:59'
     group by siteid
     order by siteid
) B ON A.siteid = B.siteid