Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
btamulis
Yak Posting Veteran
64 Posts |
Posted - 2007-02-11 : 19:45:42
|
| I have tried Books online and have queried this forum for assistance in creating a SQL view and have spent much time trying to solve on my own.I am working with only one table:Sales: SOP10200SOPTYPE ITEMNMBR ITEMDESC QUANTITY3 Widget special 43 Widget special 72 Gadget special 12 Widget special 123 Gadget special 5I want to create a view that summarizes the data based upon SOPTYPE and ITEMNMBR as follows:ITEM_NUMBER ITEM_DESC QTY_INVOICED QTY_ORDEREDWidget special 11 12Gadget special 5 1I am struggling whether to use a select statement or a CASE statement.I am able to summarize one SOPTYPE as follows:CREATE VIEW [dbo].[Tec_SOP10200_INVOICE_Qty]ASSELECT ITEMNMBR as ITEM_NUMBER, ITEMDESC as ITEM_DESC, SUM(QUANTITY) AS QTY_INVOICED FROM SOP10200WHERE SOPTYPE = 3GROUP BY ITEMNMBR, ITEMDESCBut I need more than one soptype in same viewI tried this CASE statement - Create tec_sales_viewasSELECT SOP10200.ITEMNMBR as ITEM_NUMBER , SOP10200.ITEMDESC as ITEM_DESC , SOP10200.QTY1 'QTY_INVOICED' , SOP10200.QTY2 'QTY_ORDERED' , (CASE WHEN SOP10200.SOPTYPE = 3 THEN SUM(QUANTITY) QTY1 ELSE 0) (CASE WHEN SOP10200.SOPTYPE = 2 THEN SUM(QUANTITY) QTY2 ELSE 0) END as QTY_Type FROM SOP10200 GROUP BY ITEMNMBR, ITEMDESC, QTY1, QTY2But I get error message doesn't recognize QTY1 (invalid column name)Thank you in advance for any assistance....... |
|
|
btamulis
Yak Posting Veteran
64 Posts |
Posted - 2007-02-11 : 20:23:56
|
| Incredibly, I was able to solve this by searching other postings in this forum. I ended up with something very simple - (slightly modified to include more soptypes and a totalqty column)ALTER VIEW tec_sales_sop10200_viewasselect ITEMNMBR, ITEMDESC, sum(case when SOPTYPE = '2' then QUANTITY else 0 end) as ORDER_QTY, sum(case when SOPTYPE = '3' then QUANTITY else 0 end) as INVOICE_QTY, sum(case when SOPTYPE = '2' then QUANTITY else 0 end) as RETURN_QTY, sum(case when SOPTYPE = '5' then QUANTITY else 0 end) as BACKORDER_QTY, sum(QUANTITY) as TOTALQTYfrom SOP10200group by ITEMNMBR, ITEMDESCThis works great for my purpose. Thanks to all who read......I would still be interested if there are alternative scripts - maybe temp table, etc... |
 |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-02-11 : 20:34:27
|
I would still be interested if there are alternative scripts - maybe temp table, etc...If you need a view of it, you can't use temp table. KH |
 |
|
|
|
|
|
|
|