行中的SQL结果不是列

时间:2011-07-12 20:36:58

标签: sql reporting-services

我试图在行而非列中列出查询结果。我有研究数据透视表和许多项目,并认为我会在这里发布我的问题。此查询获取了连锁餐厅的存款清单。每天可能有1个或最多5个。制造商的软件将它们列在正常交易中,而不以任何方式编号。

以下是我的查询。

use SpeedlinkDB
SELECT 
  ad.StoreID,
  (ad.Amount * -1) as anAmount    
FROM AccountDetail ad
LEFT JOIN DayFileSummary DF ON ad.StoreId = DF.StoreID and ad.EODID = DF.EODID    
WHERE 
(DATEDIFF(d, df.DF_BusinessDay, GETDATE()) = 1)    
AND ( ad.TransType = 18 )
GROUP BY 
  ad.StoreID,
  ad.Amount    
ORDER BY ad.StoreID

查询结果....

StoreID    anAmount
1104       667.28
1104       110.00
1107       750.00
1107       211.00
1107       464.20
1205       280.11
etc..

我想要的是以下......

StoreID    Deposit1    Deposit2    Deposit3    Deposit4
1104       667.28      110.00  
1107       750.00      211.00      464.20
1205       280.11

主要原因是我们使用Reporting Services显示前一天管理的摘要信息。在其他信息中,他们希望看到每个存款,销售等......

提前感谢您提供的任何帮助。

3 个答案:

答案 0 :(得分:4)

您可以使用ROW_NUMBER函数为每个StoreID分配序号,然后使用ID和密钥进行Pivot。

如果您要订购存款的其他参数(例如存款时间),您可以通过窗口条款在分区中添加订单。

像这样。

select StoreID,
       max(case DepositNumber when 1 then Deposit else null end) Deposit1
       max(case DepositNumber when 2 then Deposit else null end) Deposit2
       max(case DepositNumber when 3 then Deposit else null end) Deposit3
       max(case DepositNumber when 4 then Deposit else null end) Deposit4
       max(case DepositNumber when 5 then Deposit else null end) Deposit5
  from (
            SELECT StoreID, 
                   Deposit, 
                   ROW_NUMBER() OVER(partition by StoreID) AS DepositNumber
            from (<< Your Query above>> 
        )
   group by StoreID;

答案 1 :(得分:1)

在Rajesh Chamarthi的答案(+1)的基础上,如果你使用矩阵控制,你可以避免使用case语句和pivot:

http://www.sqlservercentral.com/articles/Reporting+Services+%28SSRS%29/63415/

你仍然需要使用Rajesh的ROW_NUMER()才能通过存款将其拆分......但如果使用矩阵控制,你可以跳过案例陈述......

SELECT 
    StoreID, 
    Deposit, 
    ROW_NUMBER() OVER(partition by StoreID) AS DepositNumber
from (<< Your Query above>>)

答案 2 :(得分:0)

感谢你们两位的帮助。第二个答案使用较少的资源,速度更快,但欣赏输入。由于我收到的错误,我的错误是用订单替换了分区。使用它们两者,我得到了我正在寻找的东西。谢谢!

SELECT 
ad.StoreID, 
ad.Amount, 
ROW_NUMBER() OVER(Partition By ad.StoreID Order by ad.StoreID) AS DepositNumber
FROM AccountDetail ad
LEFT JOIN DayFileSummary DF ON ad.StoreId = DF.StoreID and ad.EODID = DF.EODID

WHERE 
(DATEDIFF(d, df.DF_BusinessDay, GETDATE()) = 1)

AND (ad.TransType = 18)