我在SQL Server中有一个表,其中有客户使用活动和非活动卡。如果客户只有一张卡,那么它应该返回一行。如果客户有多张卡,那么我将如何返回活动卡的行,但两张卡中的金额总和是多少?
示例:
----------------------------------------
CUSTOMER | CARD | AMOUNT | STATUS
----------------------------------------
JOHN DOE | 101 | 100 | 1
JOHN DOE | 102 | 200 | 2
JANE DOE | 103 | 100 | 2
期望的输出:
----------------------------------------
CUSTOMER | CARD | AMOUNT | STATUS
----------------------------------------
JOHN DOE | 101 | 300 | 1
JANE DOE | 103 | 100 | 2
我只需要1张卡,如果客户有多张卡,我只想获得有效卡,但我需要所有卡的累积金额。在上表中,我想获得两张卡中购买John的总金额(300),但只返回活动卡(101)的行。
我已经尝试过我在这里找到的解决方案,但我的要求有点不同,因为我有一个我希望返回的值的条件。
Query to return 1 instance of a record with duplicates
SQL query to return one single record for each unique value in a column
How to return a single transaction per customer
关于金额,我可以稍后使用客户ID放置两张卡的累计金额,但对我来说现在最重要的是,如果客户有多个,则只能返回活动卡。
以下是我正在处理的查询:
select customer, card, sum(amount), min(active)
from transactions
group by customer, card, active
谢谢!
答案 0 :(得分:0)
有一个子查询,返回每个客户的最低活动值。加入这个结果:
select customer, card, amount, active
from transactions t1
join (select customer, min(active) as active
from transactions
group by customer) t2
on t1.customer = t2.customer and t1.active = t2.active
答案 1 :(得分:0)
示例数据
create table #t
(
CUSTOMER varchar (100),
CARD varchar (50),
AMOUNT varchar (100),
STATUS int
)
insert into #t values ('JOHN DOE','101','100',1)
insert into #t values ('JOHN DOE','102','200',2)
insert into #t values ('JOHN DOE','103','300',2)
insert into #t values ('JOHN DOE','101','100',1)
<强> QUERY 强> 您可以像上面一样创建一个存储的pocedur: -
CREATE PROC RESULT
AS
BEGIN
Select SUM(CONVERT (INT,AMOUNT)) AS [TOTAL AMOUNT] from #t
Select distinct CUSTOMER,CARD,AMOUNT,STATUS from #t where STATUS=1
END
<强>输出强>
EXEC RESULT
TOTAL AMOUNT
700
CUSTMER CARD AMOUNT STATUS
JOHN DUE 101 100 1