我想为列field2添加所有1和0,并将sum的输出用于新列
SELECT
field1, field2, field3, field4.....,
SUM(CASE WHEN field2= 1 THEN 1 ELSE 0 END) AS field1s,
SUM(CASE WHEN field2= 0 THEN 1 ELSE 0 END) AS field0s
FROM
dbo.TableName
GROUP BY
field1, field2, field3, field4.....;
此方法不提供我需要的输出。为了说明我的需要,让我给你看一个例子;我有列customerName
,wentShopping
。对于每个客户,我想计算他/她购物的总时间,并将输出放入新列。
我编写了SQL查询,但它没有提供每个客户的总和?
这是我得到的输出:
customerName wentShopping wentShopping0 wentShopping1
test 1 0 1
.
.
test 1 0 1
但它应该是:
customerName wentShopping wentShopping0 wentShopping1
test 1 2 2
这是因为总时间测试去购物是两次,他没有去购物的总时间也是两次
答案 0 :(得分:0)
如果您想要客户的总和,那么您需要在组中拥有客户名称。例如:
SELECT customerName
, MAX(wentShopping) AS wentShopping -- did the customer go shopping at all?
, SUM(CASE
WHEN wentshopping = 1 THEN 1 /* or other column for hours shopped */
ELSE 0
END) AS wentShopping1,
, SUM(CASE
WHEN wentShopping = 0 THEN 1
ELSE 0
END) AS wentShopping0
-- , MAX(age) AS age -- a line like this can pull in other data about the customer
FROM dbo.tablename
-- we JUST group by customerName here, since we want exactly 1 grouping per customer
-- to do our sums here
GROUP BY customerName
答案 1 :(得分:0)
我认为下面会帮助你
SELECT field1
,field3
,field4
,SUM(CASE WHEN field2 = 1 THEN 1
ELSE 0
END) AS timeShoppedFor1
,SUM(CASE WHEN field2 = 0 THEN 1
ELSE 0
END) AS timeShoppedFor0
FROM dbo.TableName
GROUP BY field1
,field3
,field4
您可以按所需的clouse添加组中的所有字段。
从评论中查询:
SELECT customerName
,wentShopping
,SUM(CASE WHEN wentShopping0 = 1 THEN 1
ELSE 0
END) AS wentShopping0
,SUM(CASE WHEN wentShopping1 = 1 THEN 1
ELSE 0
END) AS wentShopping1
FROM TableName
GROUP BY customerName
,wentShopping