473,804 Members | 2,164 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

creating data for a histogram.

I have a table, TableA with amongst other fields, a field for Qty.
Qty can range from 0 to 100.
How do I count the number of rows with a qty between 1 and 10, 11 and
20, 21 and 30, and so on using one SQL statement?

Regards,
Ciarán

Jul 23 '05
16 8107
jsfromynr (ja************ @clovertechnolo gies.com) writes:
Can we similarly replace CUBE operator in SQL Server by using simple
queries that will run on any RDBMS?


I don't use CUBE very often, so I may miss some fine detail. But the
two queries below returns the same result:

SELECT type, pub_id, SUM(price), SUM(advance)
FROM titles
GROUP BY type, pub_id WITH CUBE
ORDER BY type, pub_id

SELECT type, pub_id, SUM(price), SUM(advance)
FROM titles
GROUP BY type, pub_id
UNION
SELECT type, NULL, SUM(price), SUM(advance)
FROM titles
GROUP BY type
UNION
SELECT NULL, pub_id, SUM(price), SUM(advance)
FROM titles
GROUP BY pub_id
UNION
SELECT NULL, NULL, SUM(price), SUM(advance)
FROM titles
ORDER BY type, pub_id

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #11
Hi Erland
I am bit confused by the output produced by the Query Analyzer and
finding it bit difficult to decide which one of the following query is
faster.

In query one I am using Correlated subquery Approach and it consumes
78% of batch time when run with 2nd query but time of mere 20
micrseconds
In query two I am using functions (these functions berely takes
PolicyNumber and Endrosment No to give output and does the same query )
Approach and it consumes 22% of batch time when run with 1st query but
time of 400 micrseconds
Query 1:-
select RowId,PolicyNum ber,EndoNumber, status,SF,case when SubQ is Null
then 'No' else 'Yes' end as Lock,RCount from
(
SELECT RowId,PolicyNum ber,EndoNumber, status,SF,
(select status from InProcessData05 2005MstM WHERE status in ('pen') and
IP.PolicyNumber =PolicyNumber and IP.EndoNumber=E ndoNumber) as subQ,
(select count(*) from InProcessData05 2005MstM WHERE status in
('pen','cur') and IP.PolicyNumber =PolicyNumber and
IP.EndoNumber=E ndoNumber) as RCount
--,case when SubQ is Null then 'No' else 'Yes' end as Lock
FROM InProcessData05 2005MstM IP
WHERE status in ('cur','pen')
) X
ORDER BY PolicyNumber

select getdate()
SELECT
RowId,PolicyNum ber,EndoNumber, status,SF,dbo.f nTryGetPolicyCo unt(PolicyNumbe r,EndoNumber)
as RCount,
dbo.fnTryGetPol icyLock(PolicyN umber,EndoNumbe r) as Lock
--(select status from InProcessData05 2005MstM WHERE status in ('pen')
and IP.PolicyNumber =PolicyNumber and IP.EndoNumber=E ndoNumber) as subQ,
--(select count(*) from InProcessData05 2005MstM WHERE status in
('pen','cur') and IP.PolicyNumber =PolicyNumber and
IP.EndoNumber=E ndoNumber) as RCount
--,case when SubQ is Null then 'No' else 'Yes' end as Lock
FROM InProcessData05 2005MstM
WHERE status in ('cur','pen')
order by PolicyNumber
select getdate()
create function fnTryGetPolicyC ount(@p varchar(16),@e varchar(3))
returns int
as
begin
return (select count(*) from InProcessData05 2005MstM WHERE status in
('pen','cur') and PolicyNumber=@p and EndoNumber=@e)
end

create function fnTryGetPolicyL ock(@p varchar(16),@e varchar(3))
returns varchar(3)
as
begin
declare @Lock varchar(3)
select @Lock=status from InProcessData05 2005MstM WHERE status in
('pen') and PolicyNumber=@p and EndoNumber=@E
if @Lock is null
set @Lock='No'
else
set @Lock='Yes'

return (@Lock)
--(select status from InProcessData05 2005MstM WHERE status in ('pen')
and PolicyNumber=@p and EndoNumber=@E)
end

----------------------------------------------------------
Jatinder

Jul 23 '05 #12
jsfromynr (ja************ @clovertechnolo gies.com) writes:
I am bit confused by the output produced by the Query Analyzer and
finding it bit difficult to decide which one of the following query is
faster.

In query one I am using Correlated subquery Approach and it consumes
78% of batch time when run with 2nd query but time of mere 20
micrseconds
In query two I am using functions (these functions berely takes
PolicyNumber and Endrosment No to give output and does the same query )
Approach and it consumes 22% of batch time when run with 1st query but
time of 400 micrseconds


The difference in estimate may be because the function is not considered.

Anyway, the one way to benchmark queries is this:

DECLARE @d datetime, @tookms int
SELECT @d = getdate()
-- run query here
SELECT @tookms = datediff(ms, @d, getdate())
PRINT 'This query took ' + ltrim(str(@took ms) + ' ms to run.'

You need to consider the effect of the cache. If the two queries operates
on the same data, the easiest may be to run the queries several times
and discard the first result. You can also run DBCC DROPCLEANBUFFER S to
clean the cache, but that affects the entire server.

Also, beware that datetime has a resolution of 3.33 ms. For the
measurement method above, I have never seen any value between 0 and
13 ms. I consider values below 50 ms to be too inaccurate to be
taken as a significant. 400 ms is certainly significant.

Note: above you talk "microsecon ds". I assume this is a typo for
"millisecon ds".

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #13
Hi Erland,

Thanks for your answer and time.
Sorry for the typo error.
I can be wrong in my assumption buut isn't it that the two queries are
working in simliar fashion. Both are taking a value(or two) passing it
to inner corelated query (funtion) and getting the result.
Waiting for your reply.
Jatinder

Jul 23 '05 #14
jsfromynr (ja************ @clovertechnolo gies.com) writes:
Thanks for your answer and time.
Sorry for the typo error.
I can be wrong in my assumption buut isn't it that the two queries are
working in simliar fashion. Both are taking a value(or two) passing it
to inner corelated query (funtion) and getting the result.


Just because two queries logically are the same, that does not mean that
performance is. There is quite some overhead with calls to saclar user-
defined functions. Also, when you stuff a subquery into a scalar function,
all the optimizer sees is a call, it does not see the contents of rhe
UDF, so it cannot take any shortcuts.

Table-valued functions are different. Particularly inline functions. Table-
valued inline functions are really just macros, and the query text is
pasted into the query, so the optimizer can rearrange as it likes.

As for the estimates you saw in Query Analyzer, they are just estimates, and
I would not pay too much attention on them.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #15
Hi Erland,

Thanks Again for your time .

Explaination is good. So may I consider that the UDF will always be
little slower because the Query Optimizer can never arrange it for
optimization. but using function make query more manageable

Please correct me if my assumption is wrong.

I have yet another question (query ) .
I have two tables
One empmast which store emp current designation
Other promotion table which store the promotions of an employee during
his service.It stores the information of employee designation promotion
date.

Empmast(empid int primary key,desigid int references desigmast
,............)
PromotionDtls(e mpid int references Empmast,promota tedTo int references
desigmast, promotedFrom int references Desigmast,DateO fPromotion
smalldatetime)

EmpMast
empid desigid (current designation of employee)
1 3 ............... ............... .
2 1 ............... .........

PromotionDtls
empid promotedTo PromotedFrom effectiveDate
1 2 1 1-jan-2003
1 3 2 2-dec-2003
.............
Now I wish to use the designation Id in a query
such that if the employee data exists in Promotion Table the promotedTo
should be picked according to Effectivedate
otherwise the Empmast designation
e.g If I say desigId of employee having empid 1 on date 2-jun-2003 then
it should be desigId 2
I did this using isnull but I wish to find a better method.

select isnull( ( select top 1 promotedTo from promotionDtls where
empid=1 and effectivedate<' anygivendate' order by effectivedate desc )
, (select desigid from empmast where empid=1) )

It did give the result but looking for better method to solve this.

With regards
Jatinder Singh

Jul 23 '05 #16
jsfromynr (ja************ @clovertechnolo gies.com) writes:
I have yet another question (query ) .
Sorry for not coming back to you earlier, but I had limited time for
some days to read the posts in the newsgroups, so I deferred the
difficult stuff until later.

A general advice is that it's better to post a new problem to a new
thread. Then other people might be more keen to answer it.
I have two tables
One empmast which store emp current designation
Other promotion table which store the promotions of an employee during
his service.It stores the information of employee designation promotion
date.
...


I've now looked at the problem again, but I still could not really
understand what you are looking for. Since I don't like guessing, I
answer with the standard suggestion that you include:

o CREATE TABLE statements for your tables.
o INSERT statements with sample data.
o The desired result given the sample.

The first two makes it simple to copy and paste into Query Analyzer,
and the last makes it possible to actually produce a tested query, and
also helps to clarify what you are looking for.

It's not only that I'm lazy - neither do I like guessing.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
6702
by: Oracle3001 | last post by:
Hi All, I am trying to use JAI to build a histogram of an image i have. I have posted the code below, and the error I get at runtime. I have taken the code from the offical java examples, so I am really puzzled why it doesn't work public PlanarImage thresholding (PlanarImage source) { // set up the histogram int bins = { 256 }; double low = { 0.0D };
2
2132
by: Thomas Guettler | last post by:
Hi! I need to create some simple charts with python. A list contains integers between 0 and mymax. I want to see how the values are distributed (How many are 0, how many are mymax, ...). The result should be a small (200x200) png file. I searched a bit:
27
2631
by: ext_u | last post by:
Ok I thought I would try to take the program one thing at a time. (If you remember my last post I am trying to make a histogram with data on the size of each word) Anways first .. I obviously need to determine what a word actually is. I wrote this program on my own without looking at the book or any other resource once. #include <stdio.h> main() {
5
2671
by: firewoodtim | last post by:
I want to analyze a GIF file and retrieve the histogram data on the image (pixel quantity and color symbol for each color in the file.) Does anyone know how to use PHP to do this? I've looked through the PHP documentation, the GD image library, and the ImageMagick command-line imaging system and found very little that I could use. The best thing I've found so far is an "identify -verbose" command from ImageMagick that gives the data I...
12
2855
by: KraftDiner | last post by:
Hi, I wrote a C++ class that implements an n dimensional histogram in C++, using stl maps and vectors. I want to code this up now in Python and would like some input from this group. The C++ class was VERY simple.. std::map<std::vector<unsigned short>, unsigned long> histo; Say for example I want a 3D histogram then std::vector<unsigned short> would contains
2
4280
by: Daniel Nogradi | last post by:
How does one do a histogram on only a part of an image? This is what I found in the PIL documentation about histogram( ): """ im.histogram(mask) =list Returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). """
1
1734
by: tiggy | last post by:
Hey, I wondered if anyone knows how I can create an array to put some data into intervals ready for a histogram?? I have put data from a file into program using malloc. Then I was thinking to make the data go into the right intervals that I could do each piece of data/intervalsize which would give me a result from integer division of 0, 1, 2 etc. Is this along the right lines?? Thanks!
5
2923
by: arnuld | last post by:
this is a programme that counts the "lengths" of each word and then prints that many of stars(*) on the output . it is a modified form of K&R2 exercise 1-13. the programme runs without any compile-error BUT it has a semantic BUG: what i WANT: I want it to produce a "horizontal histogram" which tells how many characters were in the 1st word, how many characters were in the second word by writing equal number of stars, *, at the...
2
3382
by: fatenn | last post by:
I need make from the Oracle Text index of the "word-frequency histogram", this is list of the tokens in this index, where each token contains the list of documents that contain that token and frequency this token in the every dokument. Don´t anybody know how to get this data from Oracle Text index so that result will save to the table or to the text file?
2
1503
by: joebenjamin | last post by:
I am trying to write a program that will generate 100 random numbers between 1 and 50. Using these numbers, generate a list that will tell the number of random numbers that fell between 1-5, 6-10, 11-15, 16-20, ... , and 46-50. I want to then print out the results as a histogram. Basically it might look like this: 1-5 (11) *********** 6-10 (8) ******** 11-15 (12) ************ 16-20 (9) *********
0
9714
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9594
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10350
jinu1996
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10351
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9174
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7638
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6866
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5534
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3002
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.