我坚持使用SQL Server 2005数据透视表查询。
考虑以下表格及数据......
create table dbo.orders(orderid int primary key, customerid int, productid int, amount money, count int, quarter char(2))
insert into dbo.orders(orderid, customerid, productid, amount, count, quarter) values(1001, 9000, 20001, 5, 1, 'Q4')
insert into dbo.orders(orderid, customerid, productid, amount, count, quarter) values(1002, 9000, 20001, 10, 1, 'Q5')
insert into dbo.orders(orderid, customerid, productid, amount, count, quarter) values(1003, 9000, 20002, 15, 1, 'Q4')
insert into dbo.orders(orderid, customerid, productid, amount, count, quarter) values(1004, 9000, 20002, 20, 1, 'Q5')
您现在有一张包含以下记录的表...
customerid productid amount count quarter
---------- --------- ------ ----- -------
9000 20001 5.00 1 Q4
9000 20001 10.00 1 Q5
9000 20002 15.00 1 Q4
9000 20002 20.00 1 Q5
现在我有以下透视查询...
select *
from
(
select o.customerid, o.productid, o.amount, o.count, o.quarter
from dbo.orders o (nolock)
)
src
pivot
(
sum(amount)
for quarter in([Q4], [Q5])
)piv
这会产生以下结果。
customerid productid count Q4 Q5
---------- --------- ------ ----- -------
9000 20001 1 5.00 10.00
9000 20002 1 15.00 20.00
问题在于我的计数已经结束。我希望结果看起来像这样......
customerid productid count Q4 Q5
---------- --------- ------ ----- -------
9000 20001 2 5.00 10.00
9000 20002 2 15.00 20.00
如果将计数用作与productid相同的透视值,则为数据透视表。
我可以从查询中删除计数并计算为子查询,但之后我会两次访问数据库。
有没有人知道如何调整和反复计算?
谢谢
答案 0 :(得分:3)
PIVOT运算符会将一列旋转为多列,并对所有其他列执行聚合。所以列(o.customerid,o.productid,o.amount)是隐式GROUPed BY。
我认为结合PIVOT和GROUP BY可以为您提供所需的结果,如下所示:
WITH piv AS (
SELECT * FROM dbo.orders o (NOLOCK)
PIVOT (
SUM(amount) FOR quarter IN ([Q4], [Q5])
) d
)
SELECT customerid, productid, SUM(count) AS count,
SUM(Q4) AS Q4, SUM(Q5) AS Q5
FROM piv
GROUP BY customerid, productid;
CTE内部查询的第一部分将执行旋转,但不会减少行数,因为o.orderid是唯一键,并且包含在PIVOT运算符的隐式GROUP BY中。
外部查询将采用PIVOTed行和GROUP BY所需的列,即(customerid,productid)。
答案 1 :(得分:1)
不确定这是否是您为select customerid, productid
, (Select SUM(Count) From Orders O1
Where O1.productid = piv.productid
and O1.customerid = piv.customerid) [count]
, Q4, Q5
from
(
select o.customerid, o.productid, o.amount, o.count, o.quarter
from dbo.orders o (nolock)
)
src
pivot
(
sum(amount)
for quarter in([Q4], [Q5])
)piv
Group By customerid, productid, Q4, Q5
所尝试的内容,但这是我提出的内容。
customerid productid count Q4 Q5
9000 20001 2 5.00 10.00
9000 20002 2 15.00 20.00
结果:
2.0.14+20161117-3