Google Sheets Query: Possible to Group / Order by without Select?

守給你的承諾、 提交于 2021-02-07 10:19:58

问题


In Google Sheets I have multiple positive and negative numeric data entries per each day. I want to create a table using the query function, such that I have the following rows: Date, Negative, Positive, Total.

Date        Value
28/07/2016  10
28/07/2016  -0.9
28/07/2016  -20
29/07/2016  -30
29/07/2016  -12
29/07/2016  18
29/07/2016  -3
30/07/2016  7
30/07/2016  7
30/07/2016  15
30/07/2016  -1
30/07/2016  7

It looks like I could do three formulas with query function:

=query(A2:B13,"select A, sum(B) where B < 0 group by A order by A label A 'Date', sum(B) 'Negative'", -1)
=query(A2:B13,"select A, sum(B) where B > 0 group by A order by A label A 'Date', sum(B) 'Positive'", -1)
=query(A2:B13,"select A, sum(B) group by A order by A label A 'Date', sum(B) 'Total'", -1)

but the problem is that I have to select Date every time to be able to group and order by it. If I do not select A, the function returns #VALUE!. So the result looks like this:

Date        Negative    Date        Positive    Date        Total
28/07/2016  -20.9       28/07/2016  10          28/07/2016  -10.9
29/07/2016  -45         29/07/2016  18          29/07/2016  -27
30/07/2016  -1          30/07/2016  36          30/07/2016  35

Can I somehow avoid selecting Date for Positive and Total? I know I can simply hide these columns, but is there another way?


回答1:


Try combining single formula with use of double query and arrays {}:

={query(A2:B13,"select A, sum(B) where B < 0 group by A order by A label A 'Date', sum(B) 'Negative'", -1), query(query(A2:B13,"select A, sum(B) where B > 0 group by A order by A label A 'Date', sum(B) 'Positive'", -1),"select Col2"), query(query(A2:B13,"select A, sum(B) group by A order by A label A 'Date', sum(B) 'Total'", -1),"select Col2")}


This construction: query(query(...),"select Col2") will select only the second column of data.

and {data1, data2, data3} makes data2, data3 to be placed to the right in a new column.




回答2:


I don't know if it is any easier, but you could create a column C with =if(B2>0,B2,"") and a column D with =if(B2<0,B2,"") then fill them down. Then use:

=query(A2:D13,"select A, sum(D),sum(C),sum(B) where A is not null group by A order by A label A 'Date', sum(D) 'Negative',sum(C)'Positive',sum(B) 'Total'", -1)


来源:https://stackoverflow.com/questions/38689531/google-sheets-query-possible-to-group-order-by-without-select

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!