U-SQL - CASE语句的SUM

时间:2017-11-03 21:14:05

标签: c# azure azure-data-lake u-sql

我有一个客户交易表,我试图按客户和部门汇总。

savetxt

在SQL中我会做这样的事情:

Cust_id    trans_num    sku   dept   qty    price
 123         234        345    1      2      15.99
 123         345        887    1      1      12.99
 123         678        445    2      1      21.89
 234         345        998    1      1       7.99

U-SQL文档here提及SELECT Cust_id , SUM(CASE WHEN dept = 1 THEN (price * qty) ELSE 0 END ) dept_1_spend , SUM(CASE WHEN dept = 2 THEN (price * qty) ELSE 0 END ) dept_2_spend from tab1 group by Cust_id 等同于?,但我不确定如何C#这些值。

U-SQL中的等价物是什么?

3 个答案:

答案 0 :(得分:3)

您可以在C#中尝试三元运算符:

SELECT Cust_id
         , SUM(dept == 1 ? price * qty : 0) AS dept_1_spend
         , SUM(dept == 2 ? price * qty : 0) AS dept_2_spend
from tab1
group by Cust_id

答案 1 :(得分:2)

您也可以使用U-SQL PIVOT运算符,例如

@tab1 =
  SELECT *
  FROM(
  VALUES
    (123,234,345,1,2,15.99),
    (123,345,887,1,1,12.99),
    (123,678,445,2,1,21.89),
    (234,345,998,1,1,7.99)) AS T(Cust_id,trans_num,sku,dept,qty,price);


@res =
    SELECT Cust_id,
           SUM([1]) AS dept_1_spend,
           SUM([2]) AS dept_2_spend
    FROM
    (
        SELECT Cust_id, dept, price * qty AS spend
        FROM @tab1
    ) AS t
    PIVOT (SUM(spend) FOR dept IN ( 1 AS [1], 2 AS [2] )
    ) AS pvt
    GROUP BY Cust_id;


OUTPUT @res
TO "/output/sum_case.csv"
USING Outputters.Csv();

有关U-SQL的更多信息PIVOT可用here

答案 2 :(得分:1)

您甚至可以使用SQL的CASE表达式。您将需要C#==并使用AS指定列别名并使用大写字母表示关键字。但看起来像你的查询:

@tab1 =
  SELECT *
  FROM(
  VALUES
    (123,234,345,1,2,15.99),
    (123,345,887,1,1,12.99),
    (123,678,445,2,1,21.89),
    (234,345,998,1,1,7.99)) AS T(Cust_id,trans_num,sku,dept,qty,price);

@res =
  SELECT Cust_id,
         SUM(CASE WHEN dept == 1 THEN(price * qty) ELSE 0 END) AS dept_1_spend,
         SUM(CASE WHEN dept == 2 THEN(price * qty) ELSE 0 END) AS dept_2_spend
  FROM @tab1
  GROUP BY Cust_id;

OUTPUT @res
TO "/output/sum_case.csv"
USING Outputters.Csv();

我个人更喜欢C#ternary if。