我需要有关使用聚合创建列的帮助

时间:2019-01-02 21:38:19

标签: sql sql-server

以下问题基于下面列出的表,这些表中用户进行了某些交易。请记住,“用户”表的主键在“用户ID”和“站点ID”列上。

用户

User ID Site ID     Name
1        1          Arthur
2        1          Aaron
2        2          Brett

交易

Transaction ID  User ID Site ID Transaction Type    Transaction Date  Amount
4                  1       1         Sale              1/1/2017         120
6                  1       1         Refund            1/7/2017       -120
7                  2       2         Sale              1/5/2017         90
9                  2       1         Sale              12/1/2016        30
10                 2       1         Sale              1/1/2017         30
11                 2       1         Sale              2/1/2017         30
12                 2       1         Refund            2/7/2017 

   [enter image description here][1]-30
  

编写查询,该查询将返回包含以下列的表:   用户ID,网站ID,用户名,总销售额,退款总额,收取的净额

3 个答案:

答案 0 :(得分:0)

检查以下查询。

SELECT 
  t.UserId,
  t.SiteId,
  u.Name,
  sum(IIF(transaction_type = 'Sale', 1, 0) * isnull(Amount,0)) totalSales,
  sum(IIF(transaction_type = 'Refund', 1, 0) * isnull(Amount,0)) totalRefunds,
  sum(isnull(amount, 0)) NetAmount
From Transactions t
inner join Users u
  on u.UserId = t.UserId and u.SiteId = t.siteId
Group by
  t.UserId,
  t.SiteId,
  u.Name

答案 1 :(得分:0)

您似乎正在寻找条件聚合:

SELECT
    u.user_id,
    u.site_id,
    u.name,
    SUM(CASE WHEN t.transaction_type = 'Sale' THEN t.amount ELSE 0 END) total_sale,
    SUM(CASE WHEN t.transaction_type = 'Refund' THEN t.amount ELSE 0 END) total_refund,
    SUM(t.amount) total
FROM
    users AS u
    INNER JOIN transactions AS t
        ON  t.user_id = u.user_id
        AND t.site_id = u.site_id
GROUP BY
    u.user_id,
    u.site_id,
    u.name

答案 2 :(得分:0)

如果这是我的家庭作业问题,我还要添加一个总数。

SELECT  
     t.UserID
    ,t.SiteID
    ,u.Name
    ,SUM(CASE WHEN t.TranType = 'Sale' THEN t.Amount ELSE 0 END) AS tsales
    ,SUM(CASE WHEN t.TranType = 'Refund' THEN t.Amount ELSE 0 END) AS trefunds
    ,SUM(t.Amount) AS Total
FROM Transactions t
JOIN Users u ON u.SiteID = t.SiteID
             AND u.UserID = t.UserID
GROUP BY 
     t.UserID
    ,t.SiteID
    ,u.Name
UNION
SELECT  
     999 AS UserId
    ,999 AS SiteID
    ,'TOTALS:' AS [Name]
    ,SUM(CASE WHEN t.TranType = 'Sale' THEN t.Amount ELSE 0 END) AS tsales
    ,SUM(CASE WHEN t.TranType = 'Refund' THEN t.Amount ELSE 0 END) AS trefunds
    ,SUM(t.Amount) AS Total
FROM Transactions t

这将得到如下结果:

enter image description here

注意:我没想到会把两个ID列设为Varchar,我的简单解决方法是将999保留为所需的顺序。