我有一个独特的要求,我有3个审计表,任何时候进行更改都会为更改创建新记录。现在我需要创建一个视图,它将获得不同的订单ID以及在3个受尊重的表中更改它们的次数。
这是我开发的SQL
select distinct orderid as salesorderid,COUNT (*) AS SALESORDERUPDATE
FROM foobar
where ModifiedDateTime>'2015-11-01 20:44:55.107' group by Orderid
union all
select distinct orderid as salesorderid,count(*) SALESORDERUPDATE AS
from foobar1
where ModifiedDateTime>'2015-11-01 20:44:55.107' group by OrderID
union all
select distinct orderid as salesorderid,count(*)AS SALESORDERUPDATE
from foobar2
where ModifiedDateTime>'2015-11-01 20:44:55.107' group by Orderid;
现在我得到的结果是这样的 对于orderid 1,我有3个条目显示count(*)的不同值。我想在一行中总结一下
所以它会像
orderid 123 salesorderupdate(20)
as suppose to
orderId 123 salesorderupdate(10)
orderid 123 salesorderupdate(7)
orderid 123 salesorderupdate(3)
谢谢,
答案 0 :(得分:2)
像这样:
select orderID, sum(salesorderupdate)
from
(the query from your question goes here) temp
group by orderId
答案 1 :(得分:1)
使您的查询成为子表,然后选择id和总和
select distinct orderid, sum(SALESORDERUPDATE)
from (
select distinct orderid as salesorderid,COUNT (*) AS SALESORDERUPDATE
FROM foobar
where ModifiedDateTime>'2015-11-01 20:44:55.107' group by Orderid
union all
select distinct orderid as salesorderid,count(*) SALESORDERUPDATE AS
from foobar1
where ModifiedDateTime>'2015-11-01 20:44:55.107' group by OrderID
union all
select distinct orderid as salesorderid,count(*)AS SALESORDERUPDATE
from foobar2
where ModifiedDateTime>'2015-11-01 20:44:55.107' group by Orderid;
) changes group by orderid;