I’m an extreme novice running SQL SERVER 2005. I have two tables that I’m putting together in a view. The first table just has 2 columns that go into the view. One column is an ID number and the other is name. The second table is where all the data is. The columns in that table are ID, Date, Hour, PriceType, MarketType, and Price. My goal is to have a view that filters PriceType to be a fixed value, and then takes the difference of Price when MarketType is DAM from the price with the MarketType is RTM. Right now that looks like the following….
SELECT dbo.nodes.commonname,
dbo.nodes.node_id,
da.pricedate,
da.hour,
rt.price AS rtm,
da.price AS dam,
da.price - rt.price AS dart
FROM dbo.pnodes
INNER JOIN dbo.pnode_prices AS da
ON dbo.pnodes.node_id = da.pnode_id
INNER JOIN dbo.pnode_prices AS rt
ON dbo.pnodes.node_id = rt.pnode_id
AND da.pricetype = rt.pricetype
AND da.pricedate = rt.pricedate
AND da.hour = rt.hour
WHERE ( da.pricetype = 'LMP' )
AND ( da.markettype = 'DAM' )
AND ( rt.markettype = 'RTM' )
This view doesn’t take so long by itself. Sometimes I want to take it another step and have the difference between 2 views where I’ll run a query that joins the above view and takes the difference of Price where view1.CommonName=abc and view2.CommonName=xyz. When I run that query it takes 10 times as long to run as it takes to run the simple view by itself. I assume that if I did things optimally that it wouldn’t take 10x the time. Is there any low hanging fruit that I can do to improve this?
overall, your query looked ok, but running as a view, obviously isn’t working well for you. That said, I would like to offer a slight re-structuring of the query. Move the WHERE conditions into the JOIN components.
Ensure you have an index on the CommonName on the nodes table you will apply a filter against. On the price_nodes table, have a composite index on ( node_id, markettype, pricetype ).
This way, the where clause can rely exclusively on your condition of company A vs B. The rest of the joins are based on their “node_id”. I’ve also made the join to “rt” linked from the “da” since the node_id is already from pNodes to the da.node_id, so use da.Node_id to rt.node_id. It might be the one thing the engine is getting stuck on.