473,788 Members | 2,854 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Query Help, thanks!

Greetings!

Please see my data below, for each account, I would need the lastest
balance_date with the corresponding balance. Can anyone help me with
the query? Thanks a lot!

create table a
(account int
,balance_date datetime
,balance money)

insert into a values(101,'1/31/2005', 5000)
insert into a values(101,'2/28/2005', 6000)
insert into a values(102,'5/31/2005', 15000)
insert into a values(102,'6/30/2005', 10000)

Ideal Output
101 '2/28/2005' 6000
102 '6/30/2005' 10000

Sep 29 '05 #1
10 2696
SQL
Here is one way
select a.account,a.bal ance_date,a.bal ance
from
(select account,max(bal ance_date) as balancedate
from a
group by account)aTemp join a on a.account =aTemp.account
and a.balance_date =aTemp.balanced ate

http://sqlservercode.blogspot.com

Sep 29 '05 #2
> create table a
(account int
,balance_date datetime
,balance money)

Why are all your columns nullable? What is/are the key/s of this table?
Are you aware that MONEY will give you imprecisely rounded results when
you multiply or divide?

Try:

SELECT account, balance_date, balance
FROM a AS T
WHERE balance_date =
(SELECT MAX(balance_dat e)
FROM a
WHERE account = T.account) ;

--
David Portas
SQL Server MVP
--

Sep 29 '05 #3
Thanks for the reply!

As I only occationally create tables (I normally use tables that are
already available), I am not sure how to set up columns with NULL
options and key. What is the best way to set up MONEY to avoid
calculation problems? I would appreciate any suggestions, thanks!

Sep 29 '05 #4
Probably something like this. I'm guessing you have an Accounts table
somewhere as well.

CREATE TABLE account_balance s
(account_no INTEGER NOT NULL
CONSTRAINT fk_account_bala nces_accounts
FOREIGN KEY REFERENCES accounts (account_no)
,balance_date DATETIME NOT NULL
,balance NUMERIC(19,4) NOT NULL,
CONSTRAINT pk_account_bala nces
PRIMARY KEY (account_no,bal ance_date)) ;

--
David Portas
SQL Server MVP
--

Sep 29 '05 #5
another way:

select a.account,a.bal ance_date,a.bal ance
from a
where not exists
(select 1
from a a1
where a.account =a1.account
and a.balance_date <a1.balanceda te )

Sep 29 '05 #6
THANKS!

Alexander Kuznetsov wrote:
another way:

select a.account,a.bal ance_date,a.bal ance
from a
where not exists
(select 1
from a a1
where a.account =a1.account
and a.balance_date <a1.balanceda te )


Sep 29 '05 #7
David Portas wrote:
create table a
(account int
,balance_date datetime
,balance money)


Why are all your columns nullable? What is/are the key/s of this table?
Are you aware that MONEY will give you imprecisely rounded results when
you multiply or divide?

Try:

SELECT account, balance_date, balance
FROM a AS T
WHERE balance_date =
(SELECT MAX(balance_dat e)
FROM a
WHERE account = T.account) ;


David,

Are you channelling Celko? :-) Whether or not the columns are NULL or
NOT NULL depends on ANSI_NULL_DFLT_ ON/OFF - admittedly, they will be
NULL by default most of the time.

As for money, what data type should an amount of money be; money in
MSSQL is is essentially decimal(19,4), which is a precise data type (and
specifically recommended by BOL for cases where precision is required).
Ignoring the nonsense with currency symbols which MSSQL allows, and
forgetting about currencies like the old Turkish Lira (where dec(24,4)
or more might be needed in certain industries), why would there be any
reason to believe that results will be imprecise?

Simon
Sep 29 '05 #8
> Are you channelling Celko? :-)

Nah, I'm a total pussycat!
Whether or not the columns are NULL or NOT NULL depends on
ANSI_NULL_DFLT_ ON/OFF - admittedly, they will be NULL by default most of
the time.
True, but the purpose of posting DDL is to define the problem more clearly.
Rong's DDL was about as clear as mud - and not much more useful.
As for money, what data type should an amount of money be; money in MSSQL
is is essentially decimal(19,4), which is a precise data type (and
specifically recommended by BOL for cases where precision is required).
Incorrect, false and wrong! MONEY is definitively not even near equivalent
to DECIMAL(19,4). My professional advice is always that MONEY is unsuitable
for monetary amounts. See the example below for why. Now it's a fact that
DECIMAL isn't without its own issues because the coercian rules for DECIMAL
are not documented and not always well understood, but there is no excuse at
all for MONEY or SMALLMONEY.

DECLA RE
@mon1 MONEY,
@mon2 MONEY,
@mon3 MONEY,
@mon4 MONEY,
@num1 DECIMAL(19,4),
@num2 DECIMAL(19,4),
@num3 DECIMAL(19,4),
@num4 DECIMAL(19,4)

SELECT
@mon1 = 100, @mon2 = 339, @mon3 = 10000,
@num1 = 100, @num2 = 339, @num3 = 10000

SET @mon4 = @mon1/@mon2*@mon3
SET @num4 = @num1/@num2*@num3

SELECT @mon4 AS money_result,
@num4 AS numeric_result
Result:

money_result numeric_result
--------------------- ---------------------
2949.0000 2949.8525
(1 row(s) affected)

--
David Portas
SQL Server MVP
--

"Simon Hayes" <sq*@hayes.ch > wrote in message
news:43******** **@news.bluewin .ch... David Portas wrote:
create table a
(account int
,balance_date datetime
,balance money)


Why are all your columns nullable? What is/are the key/s of this table?
Are you aware that MONEY will give you imprecisely rounded results when
you multiply or divide?

Try:

SELECT account, balance_date, balance
FROM a AS T
WHERE balance_date =
(SELECT MAX(balance_dat e)
FROM a
WHERE account = T.account) ;


David,

Are you channelling Celko? :-) Whether or not the columns are NULL or NOT
NULL depends on ANSI_NULL_DFLT_ ON/OFF - admittedly, they will be NULL by
default most of the time.

As for money, what data type should an amount of money be; money in MSSQL
is is essentially decimal(19,4), which is a precise data type (and
specifically recommended by BOL for cases where precision is required).
Ignoring the nonsense with currency symbols which MSSQL allows, and
forgetting about currencies like the old Turkish Lira (where dec(24,4) or
more might be needed in certain industries), why would there be any reason
to believe that results will be imprecise?

Simon

Sep 29 '05 #9
David Portas wrote:
Are you channelling Celko? :-)

Nah, I'm a total pussycat!


Hmm, no comment... :-)

Whether or not the columns are NULL or NOT NULL depends on
ANSI_NULL_DFL T_ON/OFF - admittedly, they will be NULL by default most of
the time.

True, but the purpose of posting DDL is to define the problem more clearly.
Rong's DDL was about as clear as mud - and not much more useful.


Agreed - I was certainly splitting hairs there. If you want other people
to reproduce your results, then of course you need a script which works
the same way everywhere. Or at least as far as possible; if you really
want reproducible DDL then you need the COLLATE clause with every
character data type, and even then if your client doesn't behave the
same way as the OP's, you may find it tough to compare (in addition to
the numerous issues which I didn't even think of). Sounds like I'm
splitting hairs again...

As for money, what data type should an amount of money be; money in MSSQL
is is essentially decimal(19,4), which is a precise data type (and
specificall y recommended by BOL for cases where precision is required).

Incorrect, false and wrong! MONEY is definitively not even near equivalent
to DECIMAL(19,4). My professional advice is always that MONEY is unsuitable
for monetary amounts. See the example below for why. Now it's a fact that
DECIMAL isn't without its own issues because the coercian rules for DECIMAL
are not documented and not always well understood, but there is no excuse at
all for MONEY or SMALLMONEY.

DECLA RE
@mon1 MONEY,
@mon2 MONEY,
@mon3 MONEY,
@mon4 MONEY,
@num1 DECIMAL(19,4),
@num2 DECIMAL(19,4),
@num3 DECIMAL(19,4),
@num4 DECIMAL(19,4)

SELECT
@mon1 = 100, @mon2 = 339, @mon3 = 10000,
@num1 = 100, @num2 = 339, @num3 = 10000

SET @mon4 = @mon1/@mon2*@mon3
SET @num4 = @num1/@num2*@num3

SELECT @mon4 AS money_result,
@num4 AS numeric_result
Result:

money_result numeric_result
--------------------- ---------------------
2949.0000 2949.8525
(1 row(s) affected)


OK, this is where it gets interesting. My experience is that you do the
"right thing", so you go to the accounting department and ask for their
data storage and rounding rules, based on GAAP and EU regulations. The
answer is normally a resounding "huh?". So you essentially cover your
backside by choosing 'money', on the grounds that MS recommended it (and
you document the fact that Accounting had no objections). If and when
you have rounding errors, then you blame the accountants, quote BOL and
give a theoretical example, as you and I have just done between us.

This may seem excessively cynical, but I have to admit that I have no
experience at all of a company where anyone cares about a difference as
small as the one you've shown. Which is not to say that it's not
important to some people, simply that it's never been important to me or
my clients, in the context of the applications that I've worked on.

I suspect that this is a long-winded way of saying that you're right and
I'm wrong, but this is one issue in data modelling where I've seen very
little solid information. You've said that 'money' isn't appropriate for
monetary amounts, and it's not equivalent to dec(19,4); fair enough, but
what is the appropriate data type? Another good example is Celko's
mystical natural primary key for human beings, which he seems to think
is an SSN, despite the fact that most of the world's never heard of one...

Simon
Oct 4 '05 #10

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

Similar topics

9
3137
by: netpurpose | last post by:
I need to extract data from this table to find the lowest prices of each product as of today. The product will be listed/grouped by the name only, discarding the product code - I use SUBSTRING(ProductName, 1, CHARINDEX('(', ProductName)-2). I can get this result, but I had to use several views (totally inefficient). I think this can be done in one efficient/fast query, but I can't think of one. In the case that one query is not...
4
1880
by: sah | last post by:
I need some help with the following query: DECLARE @SRV VARCHAR(20), @date smalldatetime SET @SRV = (select @@servername) SET @date = '20040901' select Srv_Name = @SRV, DB_Name = 'DB_NAME', Table_Name = 'Info_Table', Date_of_Records = @date, count(*) AS 'Actual Total' ,
7
5972
by: Simon Bailey | last post by:
How do you created a query in VB? I have a button on a form that signifies a certain computer in a computer suite. On clicking on this button i would like to create a query searching for all details invovling that computer, for the user to then view. Any ideas on some code? Many thanks for any help.
4
2073
by: d.p. | last post by:
Hi all, I'm using MS Access 2003. Bare with me on this description....here's the situation: Imagine insurance, and working out premiums for different insured properties. The rates for calculating premiums are dependant on the country in which the client is in. Therefore, we have a Country table, with its list of rates, a client table and then the property table. Getting this is great, works fine, easy! Problem is, now I need to work out a...
36
3072
by: Liam.M | last post by:
hey guys, I have one last problem to fix, and then my database is essentially done...I would therefore very much appreciate any assistance anyone would be able to provide me with. Currently I have set up a Query to show only records that meet a certain criteria...therefore excluding all of the records that do not meet this criteria (just for the record the criteria is any record within my database that falls within two months of its "Due...
5
1943
by: darnnews | last post by:
Hi, I have been creating a database to keep track of press clippings, but I have hit a couple stumbling blocks. Any help is much appreciate. 1) Seeing if my query is done I have the following code to define a query. I run the query and then get a record deleted errors (3167) when I go to export to a spreadsheet. It works if I put in a delay between the query and the
5
7371
by: elitecodex | last post by:
Hey everyone. I have this query select * from `TableName` where `SomeIDField` 0 I can open a mysql command prompt and execute this command with no issues. However, Im trying to issue the same command inside of mysql_real_query and I keep on getting this error back. "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
2
1771
by: Haas C | last post by:
Hey all, I created a Query (in Design View) which asks the user for an "As Of Date" which would then display relevant data. I put in the Criteria Row of the Query Design for the Date field. Is there anyway to put in a default of today's date in the input box and allow the user to change it to whatever they want? Please let me know if this needs further clarification. Thanks for all your help in advance.
10
6236
by: aaronrm | last post by:
I have a real simple cross-tab query that I am trying to sum on as the action but I am getting the "data type mismatch criteria expression" error. About three queries up the food chain from this cross-tab query I am using a simple query with no grouping where I am filtering some data out in the criteria line. I have been out of access for a couple years but I remember in the past I had a solution for this but I can't remember. Any help...
6
4407
by: jsacrey | last post by:
Hey everybody, got a secnario for ya that I need a bit of help with. Access 97 using linked tables from an SQL Server 2000 machine. I've created a simple query using two tables joined by one field between them. The join field in both tables are indexed and I'm selecting 1 field from each table to lookup. The Access query is taking more than 60 second to retrieve 1 record and if I execute the same query within the Query Analyzer, it...
0
9656
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...
1
10110
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
9967
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
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
7517
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
6750
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
5398
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...
1
4069
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2894
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.