Please help with the following, I am creating a view in SQL Server 2000, the sentence is I have is this one:
SELECT TOP 100 PERCENT ITEMNMBR, SUM(TRXQTY) AS Expr1, CASE WHEN datediff(month, docdate, getdate()) = 0 THEN SUM(TRXQTY) END AS period1FROM dbo.IV30300GROUP BY ITEMNMBR, DOCDATEORDER BY itemnmbr
This runs fine, but I don't get the results I expect since I just want to group by ITEMNMBR and not DOCDATE, how can I do this, if I remove DOCDATE from the groupby list I get and error that says something like "DOCDATE not valid from the selection list since its not on an add function or the GROUPBY list"
Sorry had to translate from spanish, hope it's clear enough.
So, how can I just have on the groupby the column ITEMNMBR? Something like:
SELECT TOP 100 PERCENT ITEMNMBR, SUM(TRXQTY) AS Expr1, CASE WHEN datediff(month, docdate, getdate()) = 0 THEN SUM(TRXQTY) END AS period1FROM dbo.IV30300GROUP BY ITEMNMBRORDER BY itemnmbr
Thanks in advance
You should be able to get this to work...
SELECT TOP 100 PERCENT ITEMNMBR, SUM(TRXQTY) AS Expr1, SUM(CASE WHEN datediff(month, docdate, getdate()) = 0 THEN TRXQTY ELSE 0 END) AS period1FROM dbo.IV30300GROUP BY ITEMNMBRORDER BY itemnmbr
Jeff, Actually the sort sentence was just to "debug" the view.
Thanks for your tip, but could you explain why is it such a bad idea?
I'm sure Jeff will come up with a more complete answer, but one example is that you'll create that view, then a few weeks later, someone else will use this view to create is own view. Then the process repeats itself a few more times. Now you have a single view with 5-6 sorts, all of them useless. This is also another way to tell that it's not a good idea to build views on a mountain of views. I have no figures to give you, but the less the better.
Even if you don't build views on the sorted view, consider this... what if you want the data from the view to be in a different order? The view will still sort it one way and the query will then have to resort the data... one sort is bad enough for performance but two is worse.
My other recommendation is (almost) never write a view of a view... sometimes the "inner" view must fully materialize before the outer view can resolve especially when aggragate functions are involved... huge performance hit when that happens. I'll likely get some guff about this but if a view doesn't return from a SELECT TOP 10 * almost instantaneously, you may end up having some very significant performance problems and memory usage problems when the view scales up in rows.
Basically, the only thing I really use views for is a synonyms to tables in another database so I don't have to grant access to the other database and I can leave out "sensitive" columns. I may also create "INDEXED VIEWS" for heavy aggragation because the run pretty darned fast... they're a pain to make but they can be worth it.