如何在另一个表格中使用多行的总和进行分组

时间:2017-10-17 14:11:51

标签: sql sql-server

我有两张桌子。 TicketTicketBasket如下图所示 Ticket and TicketBasket releationship
我想选择这样的颂歌:
|的 TID |的 tDate |的客户名称 |的 EXPDATE |的 | |
| 1 | XXX | XXX | XXX | 2 | 25 |
| 2 | XXX | XXX | XXX | 2 | 20 |
| 3 | XXX | XXX | XXX | 2 | 15 |
因为我的sql命令,结果与tId进行了迭代,因为每个Ticket都可以在其中包含多个Items。
我的sql代码是:

SELECT distinct Ticket.tId,dbo.ToCustomeDate(Ticket.tDate) 'tDate',
     Ticket.customerName,dbo.ToCustomeDate(isnull(Ticket.expDate,Ticket.tDate)) 'expDate',
      Ticket.tax,

    (
        (((TicketBasket.gamePrice*TicketBasket.gameCount)-
        (((TicketBasket.gamePrice * TicketBasket.gameCount)*TicketBasket.offPrice)/100))+
        (((TicketBasket.gamePrice * TicketBasket.gameCount)-
        (((TicketBasket.gamePrice * TicketBasket.gameCount)*TicketBasket.offPrice)/100))* (Ticket.tax)/100))

    ) AS total
    FROM   Ticket right JOIN TicketBasket
    ON Ticket.tId = TicketBasket.tId

但结果是
|的 TID |的 tDate |的客户名称 |的 EXPDATE |的 | |
| 1 | XXX | XXX | XXX | 2 | 10 |
| 1 | XXX | XXX | XXX | 2 | 10 |
| 1 | XXX | XXX | XXX | 2 | 5 |
| 2 | XXX | XXX | XXX | 2 | 10 |
| 2 | XXX | XXX | XXX | 2 | 10 |
| 3 | XXX | XXX | XXX | 2 | 10 |
| 3 | XXX | XXX | XXX | 2 | 5 |

我可以用cursor处理这个问题,但我知道执行select查询是一个沉重的负担,所以感谢其他解决方案。

1 个答案:

答案 0 :(得分:1)

这应该有效..基于您的查询输出:

Select 
iq.tld, iq.tDate, iq.customerName, iq.expDate,iq.tax,
SUM(total) as newTotal
from
(
SELECT distinct Ticket.tId,dbo.ToCustomeDate(Ticket.tDate) 'tDate',
     Ticket.customerName,dbo.ToCustomeDate(isnull(Ticket.expDate,Ticket.tDate)) 'expDate',
      Ticket.tax,

    (
        (((TicketBasket.gamePrice*TicketBasket.gameCount)-
        (((TicketBasket.gamePrice * TicketBasket.gameCount)*TicketBasket.offPrice)/100))+
        (((TicketBasket.gamePrice * TicketBasket.gameCount)-
        (((TicketBasket.gamePrice * TicketBasket.gameCount)*TicketBasket.offPrice)/100))* (Ticket.tax)/100))

    ) AS total
    FROM   Ticket right JOIN TicketBasket
    ON Ticket.tId = TicketBasket.tId
)iq
group by iq.tld, iq.tDate, iq.customerName, iq.expDate,iq.tax