Showing posts with label example. Show all posts
Showing posts with label example. Show all posts

Thursday, March 29, 2012

Help with COUNT in SELECT Statement

Could someone assist with getting the count function working correctly
in this example please. I know the count function will return all rows
that do not have null values, but in this case I want to count all the
rows except those with a zero sale price, (which are unsold).

The table shows works offered for sale by an artist, with a positive
figure under SalePrice indicating a sale, and I want to count the
number sold by each auction house, and sum the sale price by auction
house. The table is as follows:

NameSalePriceAuction
Dowling12000Christies
Dowling 0Christies
Dowling10000Christies
Dowling 0Christies
Dowling 0Christies
Dowling 6000Sothebys
Dowling 0Sothebys
Dowling 0Sothebys
Dowling 8000Sothebys
Dowling 0Sothebys
Dowling 0Sothebys
Dowling 0Sothebys

When I run this query:

SELECT MyTable.Name, Count(MyTable.Name) AS [Number],
Sum(MyTable.SalePrice) AS TotalSales, MyTable.Auction
FROM MyTable
GROUP BY MyTable.Name, MyTable.Auction
HAVING (((MyTable.Name)="Dowling") AND ((Sum(MyTable.SalePrice))>0));

The results are:

NameNumberTotalSalesAuction
Dowling 5 22000 Christies
Dowling 7 14000 Sothebys

The TotalSales is correct, but the Number (Count) is incorrect, as the
rows with zero were also included. The results should be:

NameNumberTotalSalesAuction
Dowling 2 22000 Christies
Dowling 2 14000 Sothebys

How do I prevent the unsolds (zeros) being counted?

Thanks in advance,

John FurphyAssuming you also want to exclude NULL saleprices (if any):

SELECT name, COUNT(NULLIF(saleprice,0)) AS number,
SUM(saleprice) AS totalsales, auction
FROM MyTable
GROUP BY name, auction
HAVING name='Dowling' AND SUM(saleprice)>0;

--
David Portas
----
Please reply only to the newsgroup
--|||"John Furphy" <johnfurphy@.a1.com.au> wrote in message
news:4ce579e8.0312010326.115691db@.posting.google.c om...
> Could someone assist with getting the count function working correctly
> in this example please. I know the count function will return all rows
> that do not have null values, but in this case I want to count all the
> rows except those with a zero sale price, (which are unsold).
> The table shows works offered for sale by an artist, with a positive
> figure under SalePrice indicating a sale, and I want to count the
> number sold by each auction house, and sum the sale price by auction
> house. The table is as follows:
> Name SalePrice Auction
> Dowling 12000 Christies
> Dowling 0 Christies
> Dowling 10000 Christies
> Dowling 0 Christies
> Dowling 0 Christies
> Dowling 6000 Sothebys
> Dowling 0 Sothebys
> Dowling 0 Sothebys
> Dowling 8000 Sothebys
> Dowling 0 Sothebys
> Dowling 0 Sothebys
> Dowling 0 Sothebys
> When I run this query:
> SELECT MyTable.Name, Count(MyTable.Name) AS [Number],
> Sum(MyTable.SalePrice) AS TotalSales, MyTable.Auction
> FROM MyTable
> GROUP BY MyTable.Name, MyTable.Auction
> HAVING (((MyTable.Name)="Dowling") AND ((Sum(MyTable.SalePrice))>0));
> The results are:
> Name Number TotalSales Auction
> Dowling 5 22000 Christies
> Dowling 7 14000 Sothebys
> The TotalSales is correct, but the Number (Count) is incorrect, as the
> rows with zero were also included. The results should be:
> Name Number TotalSales Auction
> Dowling 2 22000 Christies
> Dowling 2 14000 Sothebys
> How do I prevent the unsolds (zeros) being counted?
>
> Thanks in advance,
> John Furphy

SELECT "Name",
COUNT(*) AS Number,
SUM(SalesPrice) AS TotalSales,
Auction
FROM MyTable
WHERE SalesPrice > 0
GROUP BY "Name", Auction

Regards,
jag

Help with constraint

Hi,
I have a table where I want a certain condition with 3 of
its fields. I want only 1 of them not to be null.
For example, if the fields are A,B,C these combinations are ok:
A B C
NULL 3432 NULL
NULL NULL 554
333 NULL NULL
Howere these are not:
A B C
NULL NULL NULL
NULL 5454 554
333 545 6858
I'm not very familiar with the syntax of constraints, and I did this:
check(
case when A is null then 0 else 1 end+
case when B is null then 0 else 1 end+
case when C is null then 0 else 1 end
=1)
but I get a syntax error.
Any ideas?
Thanks!You could do something like this.
check(
A IS NOT NULL
OR B IS NOT NULL
OR C IS NOT NULL)
"Star" wrote:

> Hi,
> I have a table where I want a certain condition with 3 of
> its fields. I want only 1 of them not to be null.
> For example, if the fields are A,B,C these combinations are ok:
> A B C
> NULL 3432 NULL
> NULL NULL 554
> 333 NULL NULL
> Howere these are not:
> A B C
> NULL NULL NULL
> NULL 5454 554
> 333 545 6858
> I'm not very familiar with the syntax of constraints, and I did this:
> check(
> case when A is null then 0 else 1 end+
> case when B is null then 0 else 1 end+
> case when C is null then 0 else 1 end
> =1)
> but I get a syntax error.
> Any ideas?
> Thanks!
>|||That doesn′t work but I appreciate your help.
Even with that condition I can have something like this:
A B C
NULL 5454 554
I want only one of them to be populated.
Patrik wrote:
> You could do something like this.
> check(
> A IS NOT NULL
> OR B IS NOT NULL
> OR C IS NOT NULL)
>
> "Star" wrote:
>|||drop table aa
go
create table aa(a int, b int, c int)
go
alter table aa add constraint chk_abc check(
(a is null and b is null and c is not null) or
(a is null and b is not null and c is null) or
(a is not null and b is null and c is null)
)
go
insert into aa values(1,null,null)
insert into aa values(null,1,null)
insert into aa values(null,null,1)
insert into aa values(1,1,null)
insert into aa values(null,1,1)
insert into aa values(1,null,1)
insert into aa values(1,1,1)
insert into aa values(null,null,null)
go
select * from aa|||I think I got it to work.
Just in case someone is interested:
(case when ([A] is null) then 0 else 1 end + case when ([B] is null)
then 0 else 1 end + case when ([C] is null) then 0 else 1 end = 1)|||Ok, misunderstood you.
Try this
check(
(case isnull(a,-1) when -1 then 0 else 1 end + case isnull(b,-1) when -1
then 0 else 1 end + case isnull(c,-1) when -1 then 0 else 1 end) = 1
)
"Star" wrote:

> That doesn′t work but I appreciate your help.
> Even with that condition I can have something like this:
> A B C
> NULL 5454 554
> I want only one of them to be populated.
>
>
> Patrik wrote:
>|||drop table aa
go
create table aa(a int, b int, c int)
go
alter table aa add constraint chk_abc check(
(a is null and b is null and c is not null) or
(a is null and b is not null and c is null) or
(a is not null and b is null and c is null)
)
go
insert into aa values(1,null,null)
insert into aa values(null,1,null)
insert into aa values(null,null,1)
insert into aa values(1,1,null)
insert into aa values(null,1,1)
insert into aa values(1,null,1)
insert into aa values(1,1,1)
insert into aa values(null,null,null)
go
select * from aa|||On Thu, 26 Jan 2006 13:51:41 -0500, Star wrote:

>Hi,
>I have a table where I want a certain condition with 3 of
>its fields. I want only 1 of them not to be null.
>For example, if the fields are A,B,C these combinations are ok:
>A B C
>NULL 3432 NULL
>NULL NULL 554
>333 NULL NULL
>Howere these are not:
>A B C
>NULL NULL NULL
>NULL 5454 554
>333 545 6858
>I'm not very familiar with the syntax of constraints, and I did this:
>check(
>case when A is null then 0 else 1 end+
>case when B is null then 0 else 1 end+
>case when C is null then 0 else 1 end
>=1)
>but I get a syntax error.
>Any ideas?
Hi Star,
Though you've gotten some alternative formulations, I fail to see why
you would have gotten syntax errors. The code below runs fine for me:
CREATE TABLE Star(A int, B int, C int,
check(case when A is null then 0 else 1 end +
case when B is null then 0 else 1 end +
case when C is null then 0 else 1 end = 1)
)
go
-- Accepted
INSERT INTO Star (A, B, C)
select 1, null, null
union all
select null, 1, null
union all
select null, null, 1
-- Rejected
INSERT INTO Star (A, B, C)
SELECT 1, 1, null
INSERT INTO Star (A, B, C)
SELECT null, null, null
INSERT INTO Star (A, B, C)
SELECT 1, 1, 1
-- Show results
select * from Star
go
DROP TABLE Star
go
Hugo Kornelis, SQL Server MVP|||>From the samp[le data, it looks like they are all positive integers, so
we can use this trick:
CHECK ( COALESCE (SIGN(a), 0)
+ COALESCE (SIGN(b), 0)
+ COALESCE (SIGN(c), 0) = 1)
if you have negative numbers use SIGN (ABS(x)) and if you have zeroes,
use SIGN (ABS(x+1))|||usually problems like this arise when mutually exclusive subtypes are
stored in one table. Is that the case? Are you considering splitting up
the table?

Monday, March 26, 2012

Help With Another Query

Hello and Thank You for your previous help,
I have a table simular to the following:
ID = int (Key)
Name= VarChar
Department = nChar
Example Data
ID Name Department
1 Chuck A
2 Mark A
3 Chuck T
4 Chuck S
5 Mark S
I am looking for a query that will Return
Name All Departments
Chuck ATS
Mark AS
Without duplicate Names.
Thanks,
ChuckHi
I'd prefer doing such things on the client side
create table w
(
id int,
t varchar(50) NOT NULL
)
insert into w values (1,'abc')
insert into w values (1,'def')
insert into w values (1,'ghi')
insert into w values (2,'ABC')
insert into w values (2,'DEF')
select * from w
create function dbo.fn_my ( @.id int)
returns varchar(100)
as
begin
declare @.w varchar(100)
set @.w=''
select @.w=@.w+t+',' from w where id=@.id
return @.w
end
select id,
dbo.fn_my (dd.id)
from
(
select distinct id from w
)
as dd
drop function dbo.fn_my
"Charles A. Lackman" <Charles@.CreateItSoftware.net> wrote in message
news:OrLlfeQXHHA.996@.TK2MSFTNGP02.phx.gbl...
> Hello and Thank You for your previous help,
> I have a table simular to the following:
> ID = int (Key)
> Name= VarChar
> Department = nChar
> Example Data
> ID Name Department
> 1 Chuck A
> 2 Mark A
> 3 Chuck T
> 4 Chuck S
> 5 Mark S
> I am looking for a query that will Return
> Name All Departments
> Chuck ATS
> Mark AS
> Without duplicate Names.
> Thanks,
> Chuck
>

Help with an SQL statement

I am adding a column to my fact table to count the number of occurrences in another field. For example, I will enter a '1' in my new field named 'Count' whenever the 'Type' field has 'Meal'. What I am doing is counting the number of meals in the system so I can add up all the costs and divide by the count to get average cost per meal.

The problem is that I don't want to count every line item. I only want to input a '1' in my 'Count' field for each meal per day. I am unsure how to do this. Here is what I have:

case when T1."Type" = 'Meal' then '1' else null end

I tried using "and max(T1."Date")" but it was not working.

Please help me develop this SQL so that I only have one count per day.

Thanks.I should give some more info to make the analysis easier...

My raw data looks like this

Date Type
20040101 Meal
20040101 Meal
20040101 Meal

I want the SQL to add a Count column and the Fact table data should look like this (one count per day).

Date Type Count
20040101 Meal 1
20040101 Meal 0
20040101 Meal 0

The only way I have been able to come close is to have a count of '1' for each line item, or to have to sum all the meals and have only one line per day. Is this possible to create without having to sum?

Thanks. Sorry I wasn't more clear.|||I still don't understand what you are trying to do. To get a count of meals, why don't you just
SELECT COUNT(*) From Table WHERE Type = 'Meal'

Do you want to count the number of days that have one meal so that if a single day has multiple meals, it just counts as one:
SELECT COUNT(*) From Table WHERE Type = 'Meal' GROUP BY datepart(year, Date), datepart(dayofyear, Date)|||Yes, I want to count one meal per day, however I still want the other line items to show as zero, because they have costs.

I'll try your SQL, but won't it drop the other 2 line items?

Thanks.|||select date expression
, count(*) as numberofmeals
, sum(costs)/count(*) as averagecostofmeal
from yourtable
group by date expression|||another solution :
select Date, Type into ##temp from yourtable group by Date, Type;
select Type,count(type) from ##temp group by type;

Help with an SQL statement

I am adding a column to my fact table to count the number of occurrences in another field. For example, I will enter a '1' in my new field named 'Count' whenever the 'Type' field has 'Meal'. What I am doing is counting the number of meals in the system so I can add up all the costs and divide by the count to get average cost per meal.

The problem is that I don't want to count every line item. I only want to input a '1' in my 'Count' field for each meal per day. I am unsure how to do this. Here is what I have:

case when T1."Type" = 'Meal' then '1' else null end

I tried using "and max(T1."Date")" but it was not working.

Please help me develop this SQL so that I only have one count per day.

Thanks.This is tough to help you do. The problem is that we (or I at least) don't understand your schema, so I'm not sure what you've got stored how.

One thing that I'd strongly suggest is to avoid using reserved words like "Count". You can use them, but it makes everything more work. In this case, I'd suggest using meal_count because it avoids the collision with a reserved word and it is more meaningful to some poor bozo like me that might try to help you!

-PatP|||This does not help. I was only giving you an example, I am using the 'Count' for the column title only, and am returning the same rows if I change the column title. I want to edit the SQL so I only count the number of days they had a meal charged.

Thanks.|||I'm sorry, I was trying to explain that I didn't know enough about your problem to help. If you can post the CREATE TABLE statements for your tables, and the SELECT statement (all of it), then I could get a lot closer. As it is, I don't know enough to give you anything more than guesses.

-PatP

Friday, March 23, 2012

Help with a Trigger.

from example a do this in Vb.
scColor.CommandText = "Update Product Set Color" & WColor.Trim & "=" &
WcolorValue & " Where Product='" & VarPubProduct & "'"
In a Trigger how can I know wich column is update Color01 or Color02 or
color03?
thanksUse the UPDATE() function [available in triggers]. This only lets you
know that the column indicated in the function was updated in at least
one row of the update. Then you'll need to compare the inserted and
deleted virtual tables to get the rows that were actually updated.
e.g.
IF UPDATE(Color01)
insert into LogTable (product, color01_old, color01_new)
select d.product, d.color01, i.color01
from deleted d
join inserted i on d.product = i.product
where d.color01 <> i.color01
Miguel Arenas wrote:
> from example a do this in Vb.
> scColor.CommandText = "Update Product Set Color" & WColor.Trim & "=" &
> WcolorValue & " Where Product='" & VarPubProduct & "'"
> In a Trigger how can I know wich column is update Color01 or Color02 or
> color03?
> thanks
>|||Thank you. This was very helpful.
"Trey Walpole" wrote:

> Use the UPDATE() function [available in triggers]. This only lets you
> know that the column indicated in the function was updated in at least
> one row of the update. Then you'll need to compare the inserted and
> deleted virtual tables to get the rows that were actually updated.
> e.g.
> IF UPDATE(Color01)
> insert into LogTable (product, color01_old, color01_new)
> select d.product, d.color01, i.color01
> from deleted d
> join inserted i on d.product = i.product
> where d.color01 <> i.color01
>
> Miguel Arenas wrote:
>

Help with a SQL statement

My problem can best be described using the Northwind db as an example.
I would like to select all Customers that have never ordered a
particular Product. Thank you.There are several way to do this
(Don′t have the Northwind here but is think I get the column names right :-
) )
Select * from Customers C
Where not Exists
(
Select * from orders O where O.CustomerId = C.CustomerId
)
--
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
"rstewart27104@.gmail.com" wrote:

> My problem can best be described using the Northwind db as an example.
> I would like to select all Customers that have never ordered a
> particular Product. Thank you.
>|||Well, wouldn't you need to tie in orderdetails and productid, since the OP
wants customers that haven't ordered a specific product, not customers who
haven't ordered at all?
(BTW, how many customers that have never ordered, would you expect to find
in the database? :-) )
A
"Jens Smeyer" <Jens@.[Remove_that][for contacting me]sqlserver2005.de>
wrote in message news:944AFED5-16A1-49C3-AA3E-190857243EEB@.microsoft.com...
> There are several way to do this
> (Don′t have the Northwind here but is think I get the column names right
> :-) )
> Select * from Customers C
> Where not Exists
> (
> Select * from orders O where O.CustomerId = C.CustomerId
> )
> --
> HTH, Jens Suessmeyer.|||Well If you want to make them an offer you sure have the customer in the
database with a customerid...
Didn′t saw the word "particular", then you should go by this:
Select * from Customers C
Where not Exists
(
Select * from orders O
inner join [Order Details] od on od.orderid = o.orderid
inner join [Products] P on o.productid = od.productid
where p.ProductName = 'SomeProduct'
and O.CustomerId = C.CustomerId
)
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
"Aaron Bertrand [SQL Server MVP]" wrote:

> Well, wouldn't you need to tie in orderdetails and productid, since the OP
> wants customers that haven't ordered a specific product, not customers who
> haven't ordered at all?
> (BTW, how many customers that have never ordered, would you expect to find
> in the database? :-) )
> A
>
>
> "Jens Sü?meyer" <Jens@.[Remove_that][for contacting me]sqlserver2005.de>
> wrote in message news:944AFED5-16A1-49C3-AA3E-190857243EEB@.microsoft.com..
.
>
>|||> Well If you want to make them an offer you sure have the customer in the
> database with a customerid...
Right, but my point was, most online stores won't have data about a customer
unless they've purchased from them once. :-)|||OK, but what would you expect from a query displaying all customers which
didn′t by anything if you refer to the online store example. If you have on
e
customer that′ll be
mankind - 1 = SelectList
;-D
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
"Aaron Bertrand [SQL Server MVP]" wrote:

> Right, but my point was, most online stores won't have data about a custom
er
> unless they've purchased from them once. :-)
>
>|||> OK, but what would you expect from a query displaying all customers which
> didn′t by anything if you refer to the online store example.
Typically, I wouldn't expect such a query to have any practical meaning. I
suppose there is probably a sliding scale, the less credible the company,
the lower their percentage of actual customers in their "customer" list.
:-)|||or
SELECT c.[CustomerID]
FROM [Customers] c
LEFT OUTER JOIN [Orders] o
ON c.[CustomerID]=o.[CustomerID]
WHERE o.[CustomerID] is null
"Jens S'meyer" <Jens@.[Remove_that][for contacting me]sqlserver2005.de>
wrote in message news:944AFED5-16A1-49C3-AA3E-190857243EEB@.microsoft.com...
> There are several way to do this
> (Dont have the Northwind here but is think I get the column names right
:-) )
> Select * from Customers C
> Where not Exists
> (
> Select * from orders O where O.CustomerId = C.CustomerId
> )
> --
> HTH, Jens Suessmeyer.
> --
> http://www.sqlserver2005.de
> --
>
> "rstewart27104@.gmail.com" wrote:
>

Monday, March 19, 2012

help with a query

I need some help creating a QUERY..
here's an example of what I need to do: say for instance my database
contains 3 values:
4012345
3012345
4055555
I want to create a query that will count the number of records where
the last 5 are unique. In the example that count would equal 2. I won't
know what the last 5 digits are.
How would I go about this? My first though would be to use DISTINCT,
but I don't know how to format the SELECT DISINCT part of the query..
is there some kind of RIGHT(field,5) method I can use?
any help would be appreciated.SELECT COUNT(DISTINCT RIGHT(colname,5))
FROM TableName
On a big table, however, this will perform horribly, because every single
row will need to be passed through the string function.
If the right-most five digits of the number mean something special, then
perhaps you should consider storing those digits in a separate column.
<kevin@.questionmark.com> wrote in message
news:1122924156.826395.283970@.g49g2000cwa.googlegroups.com...
>I need some help creating a QUERY..
> here's an example of what I need to do: say for instance my database
> contains 3 values:
> 4012345
> 3012345
> 4055555
> I want to create a query that will count the number of records where
> the last 5 are unique. In the example that count would equal 2. I won't
> know what the last 5 digits are.
> How would I go about this? My first though would be to use DISTINCT,
> but I don't know how to format the SELECT DISINCT part of the query..
> is there some kind of RIGHT(field,5) method I can use?
> any help would be appreciated.
>|||>> is there some kind of RIGHT(field,5) method I can use?
Yes.
Anith|||Please post DDL along with the sample data and expected results, so we can
better answer your question [http://www.aspfaq.com/etiquette.asp?id=5006]
How about this (completed untested, due to lack of DDL):
SELECT COUNT(*) AS Count of FROM
(SELECT DISTINCT(SUBSTRING(MadeUpColumn, 4, 4) FROM MadeUpTable) FakeTable
Do you find yourself needing to break out the right 4 digits on a regular
basis? If so, you might want to consider creating separate columns for the
leading digits and trailing digits - that way, you would not need to use
parsing functions and you could place appropriate indices on the columns to
be searched/summarized.
IHTH
Jeremy
<kevin@.questionmark.com> wrote in message
news:1122924156.826395.283970@.g49g2000cwa.googlegroups.com...
> I need some help creating a QUERY..
> here's an example of what I need to do: say for instance my database
> contains 3 values:
> 4012345
> 3012345
> 4055555
> I want to create a query that will count the number of records where
> the last 5 are unique. In the example that count would equal 2. I won't
> know what the last 5 digits are.
> How would I go about this? My first though would be to use DISTINCT,
> but I don't know how to format the SELECT DISINCT part of the query..
> is there some kind of RIGHT(field,5) method I can use?
> any help would be appreciated.
>|||Sorry, for some reason I mistook your requirement as a need to split up a
phone number, so I used the right four characters instead of the right 5
characters - this should be better:
SELECT COUNT(DISTINCT(SUBSTRING(MadeUpColumn, 3, 5)) FROM MadeUpTable
"Jeremy Williams" <jeremydwill@.netscape.net> wrote in message
news:eX8sSItlFHA.2860@.TK2MSFTNGP15.phx.gbl...
> Please post DDL along with the sample data and expected results, so we can
> better answer your question [http://www.aspfaq.com/etiquette.asp?id=5006]
> How about this (completed untested, due to lack of DDL):
> SELECT COUNT(*) AS Count of FROM
> (SELECT DISTINCT(SUBSTRING(MadeUpColumn, 4, 4) FROM MadeUpTable) FakeTable
> Do you find yourself needing to break out the right 4 digits on a regular
> basis? If so, you might want to consider creating separate columns for the
> leading digits and trailing digits - that way, you would not need to use
> parsing functions and you could place appropriate indices on the columns
to
> be searched/summarized.
> IHTH
> Jeremy
> <kevin@.questionmark.com> wrote in message
> news:1122924156.826395.283970@.g49g2000cwa.googlegroups.com...
>|||> SELECT COUNT(DISTINCT(SUBSTRING(MadeUpColumn, 3, 5)) FROM MadeUpTable
Well, this assumes the value will always be exactly 8 digits... more sample
data would be useful, but the OP said right 5 characters...|||So what are you saying, I should have used RIGHT instead of SUBSTRING, just
because the OP said they wanted the right 5 characters? :-)
Just another example of "open mouth, insert foot". Thanks for the
correction, Aaron!
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:%23pPg4btlFHA.3336@.tk2msftngp13.phx.gbl...
> Well, this assumes the value will always be exactly 8 digits... more
sample
> data would be useful, but the OP said right 5 characters...
>|||Well, I don't necessarily think your solution is bad (or constitutes
foot-in-mouth syndrome); I prefer substring myself. Just trying to pre-empt
the inevitable, "Hey, Jeremy, this only works on columns where the value has
exactly 8 digits! Thanks a LOT!" ;-)
"Jeremy Williams" <jeremydwill@.netscape.net> wrote in message
news:urH3w3tlFHA.3316@.TK2MSFTNGP14.phx.gbl...
> So what are you saying, I should have used RIGHT instead of SUBSTRING,
> just
> because the OP said they wanted the right 5 characters? :-)
> Just another example of "open mouth, insert foot". Thanks for the
> correction, Aaron!
>|||Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, data types, etc. in
your schema are. Sample data is also a good idea, along with clear
specifications. It is very hard to debug code when you do not let us
see it.
Let's get back to the basics of an RDBMS. Rows are not records; fields
are not columns; tables are not files. No wonder that you are mimicing
a COBOL program and file.
If these "last five digits" (are they CHAR(7) or INTEGER or what?)
have a meaning apart from the **column**, then they need to be modeled
as another data element.

Monday, March 12, 2012

Help with 2 datetime fields-1 stores date, the other time

Hi,
We have a lame app that uses 2 datetime(8) fields, 1 stores the date, the
other the time.
example query:

select aud_dt, aud_tm
from orders

results:
aud_dt aud_tm
2006-06-08 00:00:00.000 1900-01-01 12:32:26.287

I'm trying to create a query that give me records from the current date in
the past hour.
Here's a script that gives me todays date but I cannot figure out the time:

select aud_dt, aud_tm, datediff(d,aud_dt,getdate()), datediff(mi, aud_tm,
getdate())
from orders
where (datediff(d,aud_dt,getdate()) = 0)

results:
aud_dt aud_tm
datediff(0=today) timediff (since 1900-01-01)
2006-06-08 00:00:00.000 1900-01-01 12:32:26.287 0
55978689

I added this next part to the above query but it does not work since the
date/time is from 1900-01-01
and (datediff(mi, aud_tm, getdate()) <= 60)

Thanks for any help.rdraider wrote:
> Hi,
> We have a lame app that uses 2 datetime(8) fields, 1 stores the date, the
> other the time.
> example query:
> select aud_dt, aud_tm
> from orders
> results:
> aud_dt aud_tm
> 2006-06-08 00:00:00.000 1900-01-01 12:32:26.287
> I'm trying to create a query that give me records from the current date in
> the past hour.
> Here's a script that gives me todays date but I cannot figure out the time:
> select aud_dt, aud_tm, datediff(d,aud_dt,getdate()), datediff(mi, aud_tm,
> getdate())
> from orders
> where (datediff(d,aud_dt,getdate()) = 0)
> results:
> aud_dt aud_tm
> datediff(0=today) timediff (since 1900-01-01)
> 2006-06-08 00:00:00.000 1900-01-01 12:32:26.287 0
> 55978689
>
> I added this next part to the above query but it does not work since the
> date/time is from 1900-01-01
> and (datediff(mi, aud_tm, getdate()) <= 60)
>
> Thanks for any help.

The correct way would be to fix the database and use one datetime
column. I'll assume you already know this and that it isn't possible
for some reason.

So, if you want to combine those two into one datetime field (which you
could then use in a query however you like) you can use something like
this:

cast((cast(aud_dt as float) + cast(aud_tm as float)) as datetime)

although you might lose some precision in the miliseconds. If that's
unacceptable, you can instead do this:

convert(datetime, convert(varchar(10), aud_dt, 1) + ' ' +
convert(varchar(10), aud_tm, 14))|||These both work well. Miliseconds don't matter.

Thank you.

"ZeldorBlat" <zeldorblat@.gmail.com> wrote in message
news:1149832253.251499.139790@.h76g2000cwa.googlegr oups.com...
> rdraider wrote:
>> Hi,
>> We have a lame app that uses 2 datetime(8) fields, 1 stores the date, the
>> other the time.
>> example query:
>>
>> select aud_dt, aud_tm
>> from orders
>>
>> results:
>> aud_dt aud_tm
>> 2006-06-08 00:00:00.000 1900-01-01 12:32:26.287
>>
>> I'm trying to create a query that give me records from the current date
>> in
>> the past hour.
>> Here's a script that gives me todays date but I cannot figure out the
>> time:
>>
>> select aud_dt, aud_tm, datediff(d,aud_dt,getdate()), datediff(mi, aud_tm,
>> getdate())
>> from orders
>> where (datediff(d,aud_dt,getdate()) = 0)
>>
>> results:
>> aud_dt aud_tm
>> datediff(0=today) timediff (since 1900-01-01)
>> 2006-06-08 00:00:00.000 1900-01-01 12:32:26.287 0
>> 55978689
>>
>>
>> I added this next part to the above query but it does not work since the
>> date/time is from 1900-01-01
>> and (datediff(mi, aud_tm, getdate()) <= 60)
>>
>>
>> Thanks for any help.
> The correct way would be to fix the database and use one datetime
> column. I'll assume you already know this and that it isn't possible
> for some reason.
> So, if you want to combine those two into one datetime field (which you
> could then use in a query however you like) you can use something like
> this:
> cast((cast(aud_dt as float) + cast(aud_tm as float)) as datetime)
> although you might lose some precision in the miliseconds. If that's
> unacceptable, you can instead do this:
> convert(datetime, convert(varchar(10), aud_dt, 1) + ' ' +
> convert(varchar(10), aud_tm, 14))

Sunday, February 19, 2012

Help Req with Locking Tables...

Hi DB Gurus..

I need to lock one table ( table-level locking) as i dont want anyone to modify till i finish my stored procedure.

I need simple example on how to Lock the table and unlock..

Something like this

Lock Table Name...
...

statements go here
...

Unlock table...

Is this possible in Sql server 2000

waiting for ur replies..

Thanks in AdvanceI dont know whether this is efficient method

begin transaction

...

statements go here
...

Commit transaction|||Hey Guys..

anymore suggestions...|||Whenever I see anyone suggest locking a table, the first thing that comes to my mind is to stop SQL Server, then restart it in single user mode. While some folks consider this a bit drastic, it has about the same effect on scalability, it is far more efficient, and it is less uncertain.

-PatP