Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

sql server - How to SUM distinct values Pivot Table

I have data like this

... REF  R_UNITS  R_STOCK  COMPONENT  C_UNITS  C_STOCK  HELPER...
.................................................................
... 1    800        0        CODE1      800      500       1.....  
... 1    200        0        CODE1      200      500       1.....  
... 1    300        0        CODE1      300      500       1.....     
... 2    500      1000       CODE1      500      500       1.....   
... 2    200      1000       CODE1      200      500       1.....   
... 3    300       500       CODE1      300      500       1.....  
... 3    500       500       CODE1      500      500       1.....  
... 3    200       500       CODE1      200      500       1.....   
... 4    400        0        CODE1      400      500       1.....   
... 4    100        0        CODE1      100      500       1.....
.................................................................

And I want to pivot it like this:

COMPONENT  R_UNITS  R_STOCK  Σ C_NEEDED  C_STOCK   Σ C_TO_BUY
CODE1        3500     1500       2000      500        1500
CODE2        ...      ...         ...      ...         ...
CODE3        ...      ...         ...      ...         ...
....... 

I'd need to SUM DISTINCT by R_STOCK.

Data comes from a query in SQL-Server. I tried to group by REF and COMPONENT but it has so many sub-selects that I don't know how to.

My EXCEL doesn't support PowerPivot. Sadly, DAX is not an option

Is there any way to pivot the table the way I want by a calculated field?

EDIT: I can add new columns with SQL or M if needed

Thank you very much


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok, solved. I grouped REF, COMPONENTS, etc. using PowerQuery.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...