首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用SQL -如何聚合支付类型

使用SQL -如何聚合支付类型
EN

Stack Overflow用户
提问于 2020-05-06 19:13:06
回答 2查看 130关注 0票数 1

如何聚合PaymentType字段,以便如果客户以前使用过所有支付类型,则支付类型屏幕将显示“all”而不是“现金”、“支票”、“信用卡/借记卡”或“公司帐户”?下面是演示这个问题所需的脚本。

代码语言:javascript
复制
CREATE TABLE #Customer (
    CustomerId int,
    CustomerName nvarchar(100),
    Address nvarchar(100),
)
INSERT INTO #Customer
VALUES (1, 'Bill', '123 1st St'),
       (2, 'Fred', '111 Market St'),
       (3, 'Lisa', '01 Boulevard')

CREATE TABLE #Product (
    ProductId int,
    ProductName nvarchar(100)
)
INSERT INTO #Product
VALUES (1, 'Corn Flakes'),
       (2, 'Cheerios'),
       (3, 'Granoloa')

CREATE TABLE #PaymentType (
    PaymentId int,
    PaymentTypeName nvarchar(100)
)

INSERT INTO #PaymentType
VALUES (1, 'Cash'),
       (2, 'Check'),
       (3, 'Credit/Debit Card'),
       (4, 'Corporate Account')

CREATE TABLE #TransactionLog (
    LogId int,
    ProductId int,
    CustomerId int,
    PaymentId int,
    Amount float
)
INSERT INTO #TransactionLog
VALUES (1, 1, 1, 1, 2.00),
       (2, 2, 1, 2, 2.40),
       (3, 3, 1, 3, 1.80),
       (4, 1, 1, 4, 2.00),
       (5, 1, 2, 4, 2.00),
       (6, 2, 3, 2, 2.40)

SELECT * from #Customer
SELECT * from #Product
SELECT * from #PaymentType
SELECT * from #TransactionLog

SELECT
    c.CustomerName,
    p.ProductName,
    pt.PaymentTypeName as PaymentType
FROM #TransactionLog t
join #Product p on t.ProductId = p.ProductId
join #Customer c on t.CustomerId = c.CustomerId
join #PaymentType pt on t.PaymentId = pt.PaymentId

DROP TABLE #Customer
DROP TABLE #Product
DROP TABLE #PaymentType
DROP TABLE #TransactionLog
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-06 19:23:03

像这样的东西会有用的。但是,如果有大量数据或数据库实例不足,则可能需要对其进行调优。

代码语言:javascript
复制
;WITH
Data AS(
    SELECT
        c.CustomerName,
        p.ProductName,
        pt.PaymentTypeName as PaymentType
    FROM #TransactionLog t
    join #Product p on t.ProductId = p.ProductId
    join #Customer c on t.CustomerId = c.CustomerId
    join #PaymentType pt on t.PaymentId = pt.PaymentId
)
SELECT DISTINCT
    d.CustomerName,
    d.ProductName,
    PaymentType = IIF( ( (SELECT COUNT(DISTINCT sd.PaymentType) FROM Data sd WHERE sd.CustomerName = d.CustomerName) = 4), 
                    'All', 
                    d.PaymentType
                )
FROM
    Data d
票数 2
EN

Stack Overflow用户

发布于 2020-05-06 19:29:59

代码语言:javascript
复制
select CustomerName,case when count(distinct(PaymentType)) = 4 then 'All' end as PaymentType from (SELECT
    c.CustomerName,
    p.ProductName,
    pt.PaymentTypeName as PaymentType
FROM #TransactionLog t
join #Product p on t.ProductId = p.ProductId
join #Customer c on t.CustomerId = c.CustomerId
join #PaymentType pt on t.PaymentId = pt.PaymentId )
group by CustomerName 

这是一种方法,你可以根据你的需要调整它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61643447

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档