SQL Server结合数据问题

时间:2010-10-22 15:54:10

标签: sql sql-server sql-server-2005 sql-server-2008

嘿所有我试图将我的数据合并为一个总和。这是我现在的输出:

Amount
---------
$258.0
$400.0
$1011.0
$628.0
$628.0
$340.0
$340.0
$1764.0

当然总票房为5369美元。这是我需要的输出类型

Description   | Quantity | Price | Amount
--------------------------------------------
Fees            8          $1.50   $12.00
Redep                              $5369.00

                                   $5381.00

只有我真正需要的信息是 8 12 5369.00 5381.00

这是我查询以获取我首次发布的值:

SELECT '$' + CONVERT(varchar(50),round((CONVERT(int,Points) * .1),0)) AS 'Amount' 
  FROM tblHGP HGP,  
       OrderDetails OD, 
       tblInvoices i
  JOIN tblCS cs ON i.INumber = cs.INumber
  JOIN tblECI ac ON i.INumber = ac.INumber 
 WHERE cs.SoldTo = HGP.ECard 
   AND issued BETWEEN '2010-09-01' AND '2010-09-30 23:59:59' 
   AND Country = 'US' 
   AND HGP.iNumber = OD.orderdetail 
ORDER BY issued

2 个答案:

答案 0 :(得分:4)

如果您确实必须在查询中完成所有这些,我认为您需要类似的内容。

DECLARE @Points float, @Qty int

SELECT @Points = SUM(Points), @Qty = COUNT(*)
  FROM tblHGP HGP,  
       OrderDetails OD, 
       tblInvoices i
  JOIN tblCS cs ON i.INumber = cs.INumber
  JOIN tblECI ac ON i.INumber = ac.INumber 
 WHERE cs.SoldTo = HGP.ECard 
   AND issued BETWEEN '2010-09-01' AND '2010-09-30 23:59:59' 
   AND Country = 'US' 
   AND HGP.iNumber = OD.orderdetail 


SELECT [Description],Quantity,Price, Amount
FROM
( 
SELECT 1 AS OrderBy, 'Fees' AS [Description],@Qty AS Quantity, 1.50 AS  Price , 1.5*@Qty AS Amount
UNION ALL   
SELECT 2 AS OrderBy, 'Redep' AS [Description],NULL AS Quantity, NULL AS  Price , @Points AS Amount
UNION ALL   
SELECT 3 AS OrderBy, NULL AS [Description],NULL AS Quantity, NULL AS  Price , @Points + 1.5*@Qty AS Amount
) D
ORDER BY OrderBy  

答案 1 :(得分:1)

对于单行结果,请尝试:

SELECT count(*) fees_quantity,
       1.5 fees_price,
       1.5 * count(*) fees_amount,
       round(SUM((CONVERT(int,Points) * .1)),0)) redep_amount,
       round(SUM((CONVERT(int,Points) * .1)),0)) + 1.5 * count(*) total_amount
  FROM tblHGP HGP,  
       OrderDetails OD, 
       tblInvoices i
  JOIN tblCS cs ON i.INumber = cs.INumber
  JOIN tblECI ac ON i.INumber = ac.INumber 
 WHERE cs.SoldTo = HGP.ECard 
   AND issued BETWEEN '2010-09-01' AND '2010-09-30 23:59:59' 
   AND Country = 'US' 
   AND HGP.iNumber = OD.orderdetail 
ORDER BY issued