I've been running into more and more complexity with an application, because
as time goes on - we need more and more high-level, rolled-up information.
And so I've created views, and views that use other views.. and the queries
are getting slower and slower.
This morning, I'm working on something like this:
select
<some columns>,
"calculatedcolumn" = (select top 1 crap from stuff where
thingy='whatchamacallit')
from
someview
now, I realized that I need to really return "calculatedcolumn" in a couple
other places in the select like this - well, this is what I WANT to do:
select
<some columns>,
calculatedcolumn = (select top 1 crap from stuff where
thingy='whatchamacallit'),
otherfield = case SomeBit
when 1 then calculatedcolumn
else count(somefield)
end,
otherfield1 = case SomeotherBit
when 1 then calculatedcolumn
else sum(somefield)
end,
otherfield2 = case SomeBit2
when 1 then calculatedcolumn
else avg(somefield)
end,
otherfield3 = case SomeBit3
when 1 then calculatedcolumn
else count(somefield)
end,
from
someview
Point is, I CAN'T do that, so I have to re-run that sub-select for EACH of
these cases, and that is KILLING this stored procedure. It seems to me, that
if the database when and already got that field, for that row - I should be
able to re-use, rather than going back out additional times.
Is there a way to so this? Put simpler:
select
x = (select top 1 user_id from users),
bestUser=x,
smartestUser=x
from
Users
can I re-use "x" in that example. Thanks! 6 2777
RCS (rs****@gmail.com) writes: Is there a way to so this? Put simpler:
select x = (select top 1 user_id from users), bestUser=x, smartestUser=x from Users
can I re-use "x" in that example. Thanks!
Maybe. It depends a little what is in that subquery. If it's uncorrelated
to the main query, you could to:
SELECT x.x, bestUser = CASE WHEN ... THEN x ELSE NULL END, ...
FROM users
CROSS JOIN (SELECT TOP 1 user_id FROM users ORDER BY somecol) AS x
Here I'm using a derived table. A derived table is kind of a temp table
in the middle of the query. However, it is never materialized, and SQL
Server may not even compute the table as such, but can recast computation
order as result is the same.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se
Books Online for SQL Server SP3 at http://www.microsoft.com/sql/techinf...2000/books.asp
Thanks for the response!
In this particular case, the general gist is that this is for tracking
scores for tests.. the outer select is for general information (module name,
etc) and the subselects are tallying up total users, how many passed, how
many failed.. so in psuedo sql, it's something like this (this is very, very
over-simplied - but hopefully is clear):
select
modulename,
totalusers = (select count(*) from moduleusers where moduleid =
m.moduleid),
passed = (select count(distinct userid) from modulescores where
moduleid=m.moduleid and didpass=1)
from module as m
but it gets more complicated, I have to add some logic in for several fields
that say "if the module is a training module, then return back 'totalusers'
becuase even just finishing a practice module, should be considered
'passing'". For example.. So what I am doing now (using the same example
above) is:
select
modulename,
totalusers = (select count(*) from moduleusers where moduleid =
m.moduleid),
passed = case moduleistraining
when 1 then (select count(*) from moduleusers where moduleid =
m.moduleid) -- this is the same as "totalusers" above
else (select count(distinct userid) from modulescores where
moduleid=m.moduleid and didpass=1)
end
from module as m
But that "(select count(*) from moduleusers where moduleid = m.moduleid)"
(again, as a simple example) is in real life, a complex join, to a couple of
views and is slow - and I have to keep re-using it in other select fields.
I've never had a use for, or maybe never understood the "cross join"
statment - and I'm not clear on how you mean to use it below. Could you
elaborate?? Thanks again!!
"Erland Sommarskog" <es****@sommarskog.se> wrote in message
news:Xn**********************@127.0.0.1... RCS (rs****@gmail.com) writes: Is there a way to so this? Put simpler:
select x = (select top 1 user_id from users), bestUser=x, smartestUser=x from Users
can I re-use "x" in that example. Thanks!
Maybe. It depends a little what is in that subquery. If it's uncorrelated to the main query, you could to:
SELECT x.x, bestUser = CASE WHEN ... THEN x ELSE NULL END, ... FROM users CROSS JOIN (SELECT TOP 1 user_id FROM users ORDER BY somecol) AS x
Here I'm using a derived table. A derived table is kind of a temp table in the middle of the query. However, it is never materialized, and SQL Server may not even compute the table as such, but can recast computation order as result is the same.
-- Erland Sommarskog, SQL Server MVP, es****@sommarskog.se
Books Online for SQL Server SP3 at http://www.microsoft.com/sql/techinf...2000/books.asp
RCS (rs****@gmail.com) writes: select modulename, totalusers = (select count(*) from moduleusers where moduleid = m.moduleid), passed = case moduleistraining when 1 then (select count(*) from moduleusers where moduleid = m.moduleid) -- this is the same as "totalusers" above else (select count(distinct userid) from modulescores where moduleid=m.moduleid and didpass=1) end from module as m
SELECT m.modulname, mu.totalusres,
passed = CASE m.moduleistraing
WHEN 1 THEN mu.totalusrers
ELSE ms.didpass
END
FROM modules m
JOIN (SELECT moduleid, totalusers = COUNT(*)
FROM moduleusers
GROUP BY moduleid) mu ON m.moduleid = mu.moduleid
JOIN (SELECT moduleid, didpass = COUNT(DISTINCT userid
FROM modulescores
WHERE didpass = 1
GROUP BY moduleid) AS ms ON m.moduleid = ms.moduleid
See my preivious post for the explanation of the derived tables.
I've never had a use for, or maybe never understood the "cross join" statment - and I'm not clear on how you mean to use it below. Could you elaborate?? Thanks again!!
A cross join gives all possible combinations; this is the famous
"carteisan product". I used a cross join this case because that was
how I could translate your very loose example.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se
Books Online for SQL Server SP3 at http://www.microsoft.com/sql/techinf...2000/books.asp
Ah-HA!!! Very nice - thanks very much!!!
"Erland Sommarskog" <es****@sommarskog.se> wrote in message
news:Xn**********************@127.0.0.1... RCS (rs****@gmail.com) writes: select modulename, totalusers = (select count(*) from moduleusers where moduleid = m.moduleid), passed = case moduleistraining when 1 then (select count(*) from moduleusers where moduleid = m.moduleid) -- this is the same as "totalusers" above else (select count(distinct userid) from modulescores where moduleid=m.moduleid and didpass=1) end from module as m
SELECT m.modulname, mu.totalusres, passed = CASE m.moduleistraing WHEN 1 THEN mu.totalusrers ELSE ms.didpass END FROM modules m JOIN (SELECT moduleid, totalusers = COUNT(*) FROM moduleusers GROUP BY moduleid) mu ON m.moduleid = mu.moduleid JOIN (SELECT moduleid, didpass = COUNT(DISTINCT userid FROM modulescores WHERE didpass = 1 GROUP BY moduleid) AS ms ON m.moduleid = ms.moduleid
See my preivious post for the explanation of the derived tables.
I've never had a use for, or maybe never understood the "cross join" statment - and I'm not clear on how you mean to use it below. Could you elaborate?? Thanks again!!
A cross join gives all possible combinations; this is the famous "carteisan product". I used a cross join this case because that was how I could translate your very loose example.
-- Erland Sommarskog, SQL Server MVP, es****@sommarskog.se
Books Online for SQL Server SP3 at http://www.microsoft.com/sql/techinf...2000/books.asp
It's difficult to understand what you are really trying to do, but if
calculatedcolumn is going to be the same all the way through, DECLARE
and SET it upfront, i.e.
DECLARE @CalculatedColumn int <or whatever>
SET @CalculatedColumn = (select top 1 crap from stuff where
thingy='whatchamacallit')
then every time you need it again, just put @CalculatedColumn instead
of the whole statement that figures it out.
A variable could be used if you know the result is going to be static.
I've also run into a problem similar to this when updating a table
with calculations, but when the calculations are based off the current
row it's updating the use of a variable gets thrown out the window :(
I had to keep reselecting the result, a correlated sub-query really,
but with my update statement I used it a hell of a lot and a simple
update statement grew to over 300 lines :)
But hey, with a cursor it took 40 mins with 1.5 million rows, now it
takes 5 mins :)
I'm going to take a look into that derived table example, might be
able to speed my statements up! Cheers!
Ian
"Ellen K" <ek*******@yahoo.com> wrote in message news:<11**********************@f14g2000cwb.googleg roups.com>... It's difficult to understand what you are really trying to do, but if calculatedcolumn is going to be the same all the way through, DECLARE and SET it upfront, i.e. DECLARE @CalculatedColumn int <or whatever> SET @CalculatedColumn = (select top 1 crap from stuff where thingy='whatchamacallit')
then every time you need it again, just put @CalculatedColumn instead of the whole statement that figures it out. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Nel |
last post by:
I have a question related to the "security" issues posed by Globals ON.
It is good programming technique IMO to initialise variables, even if it's
just
$foo = 0;
$bar = "";
Surely it would...
|
by: Craig Bailey |
last post by:
Anyone recommend a good script editor for Mac OS X?
Just finished a 4-day PHP class in front of a Windows machine, and liked
the editor we used. Don't recall the name, but it gave line numbers as...
|
by: James |
last post by:
My form and results are on one page.
If I use :
if ($Company) {
$query = "Select Company, Contact
From tblworking
Where ID = $Company
Order By Company ASC";
}
|
by: Alan Walkington |
last post by:
Folks:
How can I get an /exec'ed/ process to run in the background on an XP box?
I have a monitor-like process which I am starting as
'exec("something.exe");' and, of course the exec function...
|
by: John Ryan |
last post by:
What PHP code would I use to check if submitted sites to my directory
actually exist?? I want to use something that can return the server
code to me, ie HTTP 300 OK, or whatever. Can I do this with...
|
by: Beowulf |
last post by:
Hi Guru's,
I have a query regarding using PHP to maintain a user profiles list. I
want to be able to have a form where users can fill in their profile
info (Name, hobbies etc) and attach an...
|
by: Clarice Almeida Hughes |
last post by:
tenho um index onde tenho o link pro arq css, como sao visualizados pelo
include todas as paginas aderem ao css linkado no index. so q eu preciso de
alguns links com outras cores no css, o q devo...
|
by: JW |
last post by:
I wanted have this as part of a flood control script:
<?
echo ("Flood control in place - please wait " . $floodinterval . " seconds
between postings.");
sleep(5);
// go back two pages
echo...
|
by: Frans Schmidt |
last post by:
I want to make a new database with several tables, so I did the following:
<?php
CREATE DATABASE bedrijf;
CREATE TABLE werknemers
(voornaam varchar(15),
achternaam varchar(20),
leeftijd...
|
by: sky2070 |
last post by:
Parse error: parse error, unexpected T_OBJECT_OPERATOR, expecting ')'
in c:\inetpub\wwwroot\session.php on line 19
can anyone tell me what is wrong with this code???
<?
// Define the Session...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
| |