Showing posts with label statement. Show all posts
Showing posts with label statement. Show all posts

Monday, March 26, 2012

Grouping by week in stored procedure

Hi all,

I am using the below statement to get some dates grouped by date, in my SP.

SELECT TOP 100 PERCENT COUNT(dbo.test.CallDate) AS CallCount, year(dbo.test.CallDate) AS CallYear, datepart(wk, dbo.test.CallDate) AS [Week]
FROM dbo.test

LEFT OUTER JOIN dbo.view1 ON dbo.test.CallID = dbo.view1.CallID
LEFT OUTER JOIN dbo.view2 ON dbo.test.CallID = dbo.view2.CallID

WHERE (dbo.view1.[ACCOUNT ID] = @.accountid

OR (dbo.view2.[ACCOUNT ID] = @.accountid

AND (convert(varchar(10),dbo.test.CallDate,121) BETWEEN CONVERT(DATETIME, @.StartDate, 102)AND CONVERT(DATETIME, @.EndDate, 102))
GROUP BY year(dbo.test.CallDate), datepart(wk, dbo.test.CallDate)
ORDER BY year(dbo.test.CallDate), datepart(wk, dbo.test.CallDate)

i gave startdate as 1/1/2007 and endDate as 2/18/2007

i am getting the reuslt as
count year week
42 2001 32
2 2001 39
1 2001 51
1 2002 17
1 2002 19
106 2002 21
183 2002 22
226 2002 23
.........................
...........................
1208 2007 1
1292 2007 2

actually i should get only the last 2 rows.
Can anyone please point out, why i am getting the 2001, 2002 data? and how to fix that?

Thanks

Looks to me like you've got your bracketing wrong round your OR clause...

It's currently WHERE ( A OR (B AND C))

Shouldn't it be WHERE (A OR B) AND C?

|||

Thanks

Great help

It worked

Wednesday, March 21, 2012

Grouped information from two tables

Hi,

I have two statements which when I join by a union statement give the folowing:

2005 11 0.000000
2005 12 0.000000
2006 1 0.000000
2006 1 50813.058500
2006 10 0.000000
2006 11 0.000000
2006 12 0.000000
2006 12 63224.511250
2006 2 0.000000
2006 2 59164.234500
2006 3 0.000000
2006 4 0.000000
2006 5 0.000000
2006 6 0.000000
2006 6 82442.570750
2006 7 0.000000
2006 7 61809.497750
2006 8 0.000000
2006 9 0.000000
2007 1 0.000000
2007 2 0.000000
2007 3 0.000000
2007 4 0.000000
2007 5 0.000000
2007 6 0.000000
2007 7 0.000000
2007 8 0.000000

What I want is to merge the values

2006 1 0.000000
2006 1 50813.058500

into one row, the months with zero figures are required.

Thanks

Not the best of descriptions, but I have now solved this problem.

Answer = Ist table joins to second table (Select statement) via a right outer join.

sql

Grouped by Using aliased names

Hi,

I have a select statement that gives me an output as follows:

Date Store Num Location
4-5-2007 0001 NY
4-5-2007 0002 NY
4-5-2007 0002 NY
4-4-2007 0003 PA
4-4-2007 0002 PA

The store num and location columns are derived like so:
LEFT(Table.WholeField, 4) AS 'Store Num',
RIGHT(LEFT(Table.WholeField, 6), 2) AS 'Location'

The problem I am running into is that I have been tasked to write a select statement that sums up distinct values for Store Num and Location. The output should look something like this :

Date Store Num Location Num
4-5-2007 0002 NY 2

However, 'Store Num' and 'Location' comes from one field by design. I have written a select statement that uses the GROUP BY function to get the correct output. However, I am receiving an invalid column name error because I am using an aliased name.

Does anyone have any insight into the error or a possible workaround.

Thanks,
V.Don't use the alias in the Group By, use the expression instead.

GROUP BY LEFT(Table.WholeField, 4), RIGHT(LEFT(Table.WholeField, 6), 2)

or just bury the original query as a subquery, and then sum and group by.

The first version seems "cleaner" to me though|||Thanks for the quick response. The Grouping by for the expressions works.

However, I am still getting:

Date Store Num Location Num
4-5-2007 0002 NY 1
4-5-2007 0002 NY 1

However, I am looking for :

Date Store Num Location Num
4-5-2007 0002 NY 2

Shouldn't the group by statement work with a correct count(*) or do I have to issue counts for the two separate columns?|||Can you post the SQL statement?|||Actually, I figured it out. Thanks for your help! Not thinking straight for some reason today!|||I don't see why this wouldn't work

SELECT [DATE],
LEFT(#TMP.WholeField, 4) AS 'Store Num',
RIGHT(LEFT(#TMP.WholeField, 6), 2) AS 'Location',
COUNT(*)
FROM #TMP
GROUP BY [DATE],
LEFT(#TMP.WholeField, 4),
RIGHT(LEFT(#TMP.WholeField, 6), 2)

That yields

Date Store Num Location Num
4-4-2007 0002 PA 1
4-4-2007 0003 PA 1
4-5-2007 0001 NY 1
4-5-2007 0002 NY 2|||I was using a convert function to take the timestamp field Date and convert it to a MM-DD-YYYY format. However, in the group by statement i was using just the Fieldname Date. When I added the convert function to the group by, it worked.

Group Sum over multiple pages with IIF

I am using an IIF statement to sum a group of detail records that spans more
than 1 page. The sum looks like this:
Sum(IIf(Fields!MySwitch.Value = 'A', Fields!MyValue.Value,0))
Im doing the sum in the table1_group1 footer and it works fine if all the
data in the group remains on the same page, but once it is expanded to 2 or
more pages I get #Error. Any suggestions?
Michael CIf you can bring from a query then it is really good instead of summing two
pages rows.
Amarnath
"Michael C" wrote:
> I am using an IIF statement to sum a group of detail records that spans more
> than 1 page. The sum looks like this:
> Sum(IIf(Fields!MySwitch.Value = 'A', Fields!MyValue.Value,0))
> Im doing the sum in the table1_group1 footer and it works fine if all the
> data in the group remains on the same page, but once it is expanded to 2 or
> more pages I get #Error. Any suggestions?
> Michael C

Group SQL Select Statement

Hi,

I am bloody amateure and I was wondering if someone could help me edit
the statement below so it groups the field SCDMASTER.SCTY_CLASS_CODE
and creates one field called "total balance" equalling
CUSTODY_BALANCE.OPENING_BALANCE + CUSTODY_BALANCE.DEPOSIT_AMOUNT -
CUSTODY_BALANCE.WITHDRAWAL_AMOUNT

SELECT
CUSTODY_BALANCE.APPLICATIONCYCLEDATE,
CUSTODY_BALANCE.ASSET_ID,
SCDMASTER.SCTY_CLASS_CODE,
CUSTODY_BALANCE.OPENING_BALANCE,
CUSTODY_BALANCE.DEPOSIT_AMOUNT,
CUSTODY_BALANCE.WITHDRAWAL_AMOUNT
FROM
FPMCAPSHIST.CUSTODY_BALANCE CUSTODY_BALANCE,
CAPSREPORT.SCDMASTER SCDMASTER
WHERE
CUSTODY_BALANCE.ASSET_ID = SCDMASTER.CUSIP_ID AND
((CUSTODY_BALANCE.APPLICATIONCYCLEDATE={ts '2007-03-21 00:00:00'}) AND
(SCDMASTER.SCTY_CLASS_CODE Not In
('BILL','NOTE','BOND','CD','BD','CB','TINT','TPRN' ,'CA','YD')))

Thanks,

AndreasSomething like this=

Select
SCDMASTER.SCTY_CLASS_CODE,
sum(CUSTODY_BALANCE.OPENING_BALANCE +
CUSTODY_BALANCE.DEPOSIT_AMOUNT -CUSTODY_BALANCE.WITHDRAWAL_AMOUNT)

from
PMCAPSHIST.CUSTODY_BALANCE CUSTODY_BALANCE,
CAPSREPORT.SCDMASTER SCDMASTER
where
CUSTODY_BALANCE.ASSET_ID = SCDMASTER.CUSIP_ID AND
((CUSTODY_BALANCE.APPLICATIONCYCLEDATE={ts '2007-03-21 00:00:00'}) AND
(SCDMASTER.SCTY_CLASS_CODE Not In
('BILL','NOTE','BOND','CD','BD','CB','TINT','TPRN' ,'CA','YD')))
group by
SCDMASTER.SCTY_CLASS_CODE

MC

"Andreas" <andreas.strzodka@.ny.frb.orgwrote in message
news:1174673610.080198.22590@.y66g2000hsf.googlegro ups.com...

Quote:

Originally Posted by

Hi,
>
I am bloody amateure and I was wondering if someone could help me edit
the statement below so it groups the field SCDMASTER.SCTY_CLASS_CODE
and creates one field called "total balance" equalling
CUSTODY_BALANCE.OPENING_BALANCE + CUSTODY_BALANCE.DEPOSIT_AMOUNT -
CUSTODY_BALANCE.WITHDRAWAL_AMOUNT
>
SELECT
CUSTODY_BALANCE.APPLICATIONCYCLEDATE,
CUSTODY_BALANCE.ASSET_ID,
SCDMASTER.SCTY_CLASS_CODE,
CUSTODY_BALANCE.OPENING_BALANCE,
CUSTODY_BALANCE.DEPOSIT_AMOUNT,
CUSTODY_BALANCE.WITHDRAWAL_AMOUNT
FROM
FPMCAPSHIST.CUSTODY_BALANCE CUSTODY_BALANCE,
CAPSREPORT.SCDMASTER SCDMASTER
WHERE
CUSTODY_BALANCE.ASSET_ID = SCDMASTER.CUSIP_ID AND
((CUSTODY_BALANCE.APPLICATIONCYCLEDATE={ts '2007-03-21 00:00:00'}) AND
(SCDMASTER.SCTY_CLASS_CODE Not In
('BILL','NOTE','BOND','CD','BD','CB','TINT','TPRN' ,'CA','YD')))
>
Thanks,
>
Andreas
>

|||MS Query tells me ORA-00979: not a GROUP BY expression. Are there only
certain fields that I can group by?

On Mar 23, 2:22 pm, "MC" <marko.NOSPAMc...@.gmail.comwrote:

Quote:

Originally Posted by

Something like this=
>
Select
SCDMASTER.SCTY_CLASS_CODE,
sum(CUSTODY_BALANCE.OPENING_BALANCE +
CUSTODY_BALANCE.DEPOSIT_AMOUNT -CUSTODY_BALANCE.WITHDRAWAL_AMOUNT)
>
from
PMCAPSHIST.CUSTODY_BALANCE CUSTODY_BALANCE,
CAPSREPORT.SCDMASTER SCDMASTER
where
CUSTODY_BALANCE.ASSET_ID = SCDMASTER.CUSIP_ID AND
((CUSTODY_BALANCE.APPLICATIONCYCLEDATE={ts '2007-03-21 00:00:00'}) AND
(SCDMASTER.SCTY_CLASS_CODE Not In
('BILL','NOTE','BOND','CD','BD','CB','TINT','TPRN' ,'CA','YD')))
group by
SCDMASTER.SCTY_CLASS_CODE
>
MC
>
"Andreas" <andreas.strzo...@.ny.frb.orgwrote in message
>
news:1174673610.080198.22590@.y66g2000hsf.googlegro ups.com...
>
>
>

Quote:

Originally Posted by

Hi,


>

Quote:

Originally Posted by

I am bloody amateure and I was wondering if someone could help me edit
the statement below so it groups the field SCDMASTER.SCTY_CLASS_CODE
and creates one field called "total balance" equalling
CUSTODY_BALANCE.OPENING_BALANCE + CUSTODY_BALANCE.DEPOSIT_AMOUNT -
CUSTODY_BALANCE.WITHDRAWAL_AMOUNT


>

Quote:

Originally Posted by

SELECT
CUSTODY_BALANCE.APPLICATIONCYCLEDATE,
CUSTODY_BALANCE.ASSET_ID,
SCDMASTER.SCTY_CLASS_CODE,
CUSTODY_BALANCE.OPENING_BALANCE,
CUSTODY_BALANCE.DEPOSIT_AMOUNT,
CUSTODY_BALANCE.WITHDRAWAL_AMOUNT
FROM
FPMCAPSHIST.CUSTODY_BALANCE CUSTODY_BALANCE,
CAPSREPORT.SCDMASTER SCDMASTER
WHERE
CUSTODY_BALANCE.ASSET_ID = SCDMASTER.CUSIP_ID AND
((CUSTODY_BALANCE.APPLICATIONCYCLEDATE={ts '2007-03-21 00:00:00'}) AND
(SCDMASTER.SCTY_CLASS_CODE Not In
('BILL','NOTE','BOND','CD','BD','CB','TINT','TPRN' ,'CA','YD')))


>

Quote:

Originally Posted by

Thanks,


>

Quote:

Originally Posted by

Andreas- Hide quoted text -


>
- Show quoted text -

|||Andreas wrote:

Quote:

Originally Posted by

MS Query tells me ORA-00979: not a GROUP BY expression. Are there only
certain fields that I can group by?


Did you add any fields to the SELECT line? If so, then you need to
also add them to the GROUP BY line.

MC's query looks correct to me, though I would personally link the
tables using JOIN instead of WHERE, and assign a field name to the
computed total:

select
SCDMASTER.SCTY_CLASS_CODE,
sum(CUSTODY_BALANCE.OPENING_BALANCE
+ CUSTODY_BALANCE.DEPOSIT_AMOUNT
- CUSTODY_BALANCE.WITHDRAWAL_AMOUNT) as TotalBalance
from PMCAPSHIST.CUSTODY_BALANCE CUSTODY_BALANCE
join CAPSREPORT.SCDMASTER SCDMASTER
on CUSTODY_BALANCE.ASSET_ID = SCDMASTER.CUSIP_ID
where CUSTODY_BALANCE.APPLICATIONCYCLEDATE = {ts '2007-03-21 00:00:00'}
and SCDMASTER.SCTY_CLASS_CODE not in (
'BILL','NOTE','BOND','CD','BD','CB','TINT','TPRN', 'CA','YD'
)
group by SCDMASTER.SCTY_CLASS_CODE

group results into a string

how to group results from a select statement with single column into a comma
separated string? e.g.
results
--
a
b
c
...
string:
a, b, c, ...nono
I suggest you doing such operations on the client side
create table #test
(
col char(1)
)
insert into #test values ('a')
insert into #test values ('b')
insert into #test values ('c')
declare @.str varchar(20)
set @.str=''
select @.str=@.str+coalesce(col,'')+';' from #test
select @.str
"nonno" <nonno@.discussions.microsoft.com> wrote in message
news:BFA2B825-A041-4775-9692-1D1C5E0490AE@.microsoft.com...
> how to group results from a select statement with single column into a
comma
> separated string? e.g.
> results
> --
> a
> b
> c
> ...
> string:
> a, b, c, ...|||how can I do that in SQL Server?
"Uri Dimant" wrote:

> nono
> I suggest you doing such operations on the client side
> create table #test
> (
> col char(1)
> )
> insert into #test values ('a')
> insert into #test values ('b')
> insert into #test values ('c')
> declare @.str varchar(20)
> set @.str=''
> select @.str=@.str+coalesce(col,'')+';' from #test
> select @.str
>
> "nonno" <nonno@.discussions.microsoft.com> wrote in message
> news:BFA2B825-A041-4775-9692-1D1C5E0490AE@.microsoft.com...
> comma
>
>|||I did show you , did not I?
"nonno" <nonno@.discussions.microsoft.com> wrote in message
news:C9E42970-F176-4B03-ADA2-7ABFCEC1B944@.microsoft.com...
> how can I do that in SQL Server?
> "Uri Dimant" wrote:
>|||Thx Uri! It's really fantastic! Can u tell me what's the coalesce function
used for?
"Uri Dimant" wrote:

> I did show you , did not I?
>
> "nonno" <nonno@.discussions.microsoft.com> wrote in message
> news:C9E42970-F176-4B03-ADA2-7ABFCEC1B944@.microsoft.com...
>
>|||BOL says:
COALESCE
Returns the first nonnull expression among its arguments
Fore more details please refer to the BOL.
"nonno" <nonno@.discussions.microsoft.com> wrote in message
news:DB38C965-1514-4560-97ED-0C36AB7DC2F8@.microsoft.com...
> Thx Uri! It's really fantastic! Can u tell me what's the coalesce function
> used for?
> "Uri Dimant" wrote:
>
into a|||> Thx Uri! It's really fantastic!
Note that this method is also not supported, and does not guarantee correct
results in all possible cases.
Dejan Sarka, SQL Server MVP
Associate Mentor
www.SolidQualityLearning.com|||Uri,
Would you mind mentioning the potential drawbacks of this method while
suggesting it, at least in the future? Several newbies with limited SQL
exposure tend to misunderstand such constructs as a valid SQL queries and
may even pass onto others as a recommended approach.
Anith|||Anith
If you read my post carefully I did mention what I would have done in such
situations

>I suggest you doing such operations on the client side
"Anith Sen" <anith@.bizdatasolutions.com> wrote in message
news:%23lPkKPqPFHA.3336@.TK2MSFTNGP09.phx.gbl...
> Uri,
>
> Would you mind mentioning the potential drawbacks of this method while
> suggesting it, at least in the future? Several newbies with limited SQL
> exposure tend to misunderstand such constructs as a valid SQL queries and
> may even pass onto others as a recommended approach.
> --
> Anith
>|||>> If you read my post carefully I did mention what I would have done in
Ah..I did not notice that, my apologies :-(
Anith

Monday, March 12, 2012

GROUP BY/ HAVING CLAUSE problem

I'm trying to set up my adhoc query to return just one single record, which is aliased as 'foreign' in my sql statement (which is just the total amount of foreign overseas orders for just one day. All Sale_Type_Ids over 2 [integer datatype] are foreign orders):

SELECT SUM(CASE WHEN Orders.Sale_Type_Id > 2 THEN Orders.Sale_Type_Id ELSE NULL END) AS foreign
FROM Orders INNER JOIN
Processing ON Orders.ID = Processing.Order_ID
WHERE (Processing.Orderdate = '20050915') AND (Processing.status = 1)
GROUP BY CASE WHEN Orders.Sale_Type_Id > 2 THEN Orders.Sale_Type_Id ELSE NULL END
HAVING (SUM(CASE WHEN Orders.Sale_Type_Id > 2 THEN Orders.Sale_Type_Id ELSE NULL END) >= 0)

..but my resultset is returning two records. If I remove the HAVING clause, it will return three records, with one being blank.
?
.netsports

In caculations COUNT (* ) is the only aggregate function in SQL Server that caculates NULL values, so your results will be different if you use COUNT (* ) if any of you columns allow NULLs. Try the link below for more about SQL Server NULLs. Hope this helps.
http://www.akadia.com/services/dealing_with_null_values.html|||i am using four table(ForumMain,ForumThreads,ReplyToThread,Authentication) in my forum.I have 4 asp.net pages in this forum. On the very first page, I am showing the Main category of forums.i.e all forums,last thread posted,total threads so far and the total number of replies to each thead and of course the name of the user who generated or added last thread.
To do this, i am using count function to count the total replies to each thread,RepliesToThread table is doing that(not counting total threads yet),Forum Category field from the ForumMain table,ThreadName from the ForumThreads table and the username from the Authentication table.
I am using Group By clause as well but every time a new thread is added from AddThread.aspx page, the name of the main category which the new thread is added into, is repeated on the main page.
i.e. if I add a new thread in main category DATABASE, and this main category has already one thread, the main page show me like
DATABASE already existing category.
date:25/09/2005
DATABASE new category
date:26/09/2005
rather than it should show me
DATABASE new category
date:26/09/2005
What should I do to avoid this repetition?
Thanks in advance.|||Try the link below and see if GROUP BY with CUBE or ROLLUP operator will help with you problem and some restrictions apply. Hope this helps.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_sa-ses_9sfo.asp|||Caddre, this linke you providehttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_sa-ses_9sfo.asp is not providing help to solve my problem.
I am looking forward to more helpful replies from you or anybody else.|||Hi,
You're summingSale_Type_Id values from Orders table. I thinks this is not what you want to get. You can Count theSale_Type_Id values to have the number of orders.

SELECT SUM(CASE WHEN Orders.Sale_Type_Id > 2 THEN Orders.Sale_Type_Id ELSE NULL END) AS [foreign]
And if your records in Orders table have Sale_Type_Id values greaterthan 2, for each distinct value of Sale_Type_Id you'll get a differentrow.
Because you group your records due to Sale_Type_Id's. Note that if itis 2 or less. You group them as nulls. And remove only the null groupby using the Having clause.
So you still have groups having Sale_Type_Id's greater than 2
I hope it is helpfull
Eralper
http://www.eralper.com

Group by, ignore common words

When using GROUP BY to sort the results of a select statement, is it
possible to have it ignore certain common words. i.e "The", "A".
For instance, say you were sorting a list of book titles; you would
want "The Promise of Happiness" to be near "Pride and Prejudice", not
"Theatre Talk: Voices of Irish Theatre Practitioners".
Thanks.A) GROUP BY is not used for sorting. Use ORDER BY for sorting. GROUP BY
can use other algorithms than sorting for what it does (grouping) so it
can't be trusted to always return a sorted order.
B) Not easily... Can you store 'The Promise of Happiness" as "Promise of
Happiness, The" ?
Adam Machanic
SQL Server MVP
http://www.sqljunkies.com/weblog/amachanic
--
"never-aways" <nospam@.nospam.com> wrote in message
news:rbtr21l5lnfu33brj4it87rornnf9ubfcl@.
4ax.com...
> When using GROUP BY to sort the results of a select statement, is it
> possible to have it ignore certain common words. i.e "The", "A".
> For instance, say you were sorting a list of book titles; you would
> want "The Promise of Happiness" to be near "Pride and Prejudice", not
> "Theatre Talk: Voices of Irish Theatre Practitioners".
> Thanks.|||What about creating a user defined function that returns the "stripped"
value? You could order by on that.|||What about using this in the order by
SELECT
BookTitle
FROM
BookTitles
ORDER BY
REPLACE(SUBSTRING(BookTitle, 1, 4), 'The ', '') +
SUBSTRING(BookTitle, 5, LEN(BookTitle))
It should work, as long as there aren't any other characters except a space
after "the".
Simon Worth
"never-aways" <nospam@.nospam.com> wrote in message
news:rbtr21l5lnfu33brj4it87rornnf9ubfcl@.
4ax.com...
> When using GROUP BY to sort the results of a select statement, is it
> possible to have it ignore certain common words. i.e "The", "A".
> For instance, say you were sorting a list of book titles; you would
> want "The Promise of Happiness" to be near "Pride and Prejudice", not
> "Theatre Talk: Voices of Irish Theatre Practitioners".
> Thanks.

GROUP BY syntax

I'm trying to group rows in ItemKey to produce a sum total of prices. Then
update ItemKeyprice. The select statement works, but I get the below error.
Where is my syntax wrong?
thanks
UPDATE ItemKeyPrice
SET RegPrice =
(SELECT ItemKey.KeyNumber, SUM(ItemKey.Price) AS PriceInd
FROM ItemKey INNER JOIN ItemKeyPrice ON ItemKey.KeyNumber =
ItemKeyPrice.KeyNumber
GROUP BY ItemKey.KeyNumber)
error: Only one expression can be specified in the select list when the
subquery is not introduced with EXISTS.shank
(untested)
UPDATE ItemKeyPrice
SET RegPrice =
(SELECT SUM(ItemKey.Price) AS PriceInd
FROM ItemKey INNER JOIN ItemKeyPrice ON ItemKey.KeyNumber =
ItemKeyPrice.KeyNumber
GROUP BY ItemKey.KeyNumber)
Note: Without seeing your table stucture + samle data I could only guess
,it is possible yo9u get an error like
"Subquery returned more than 1 value."
"shank" <shank@.tampabay.rr.com> wrote in message
news:eTrms$l$FHA.1288@.TK2MSFTNGP09.phx.gbl...
> I'm trying to group rows in ItemKey to produce a sum total of prices. Then
> update ItemKeyprice. The select statement works, but I get the below
> error. Where is my syntax wrong?
> thanks
> UPDATE ItemKeyPrice
> SET RegPrice =
> (SELECT ItemKey.KeyNumber, SUM(ItemKey.Price) AS PriceInd
> FROM ItemKey INNER JOIN ItemKeyPrice ON ItemKey.KeyNumber =
> ItemKeyPrice.KeyNumber
> GROUP BY ItemKey.KeyNumber)
> error: Only one expression can be specified in the select list when the
> subquery is not introduced with EXISTS.
>|||shank (shank@.tampabay.rr.com) writes:
> I'm trying to group rows in ItemKey to produce a sum total of prices.
> Then update ItemKeyprice. The select statement works, but I get the
> below error. Where is my syntax wrong?
> thanks
> UPDATE ItemKeyPrice
> SET RegPrice =
> (SELECT ItemKey.KeyNumber, SUM(ItemKey.Price) AS PriceInd
> FROM ItemKey INNER JOIN ItemKeyPrice ON ItemKey.KeyNumber =
> ItemKeyPrice.KeyNumber
> GROUP BY ItemKey.KeyNumber)
> error: Only one expression can be specified in the select list when the
> subquery is not introduced with EXISTS.
The immediate error is the inclusion of ItemKey.KeyNumber in the Select
list. You are assigning RegPrice value, but you are sending it two
values.
However, when you fix that error, you will get another error saying that
subquery returned more than one value.
Here are two ways of writing what I think you want to achieve:
UPDATE ItemKeyPrice
SET RegPrice = (SELECT SUM(ItemKey.Price)
FROM ItemKey
WHERE ItemKey.KeyNumber = ItemKeyPrice.KeyNumber)
UPDATE ItemKeyPrice
SET RegPrice = ik.totprice
FROM ItemKeyPrice ikp
JOIN (SELECT KeyNumber, totprice = SUM(ItemKey.Price)
FROM ItemKey
GROUP BY KeyNumber) AS ik ON ik.KeyNumber = ikp.KeyNumber
The first uses a correlated subquery, and this syntax is by the ANSI
standard and should run on any DBMS. The second uses a FROM clause in
the UPDATE statement. This syntax is particular to MS SQL Server and
Sybase, and thus less portable. This query also includes a derived
table (which is part of ANSI SQL) to compute the sums per key.
While the first syntax is portable, my preference is very strongly
for the second, as it is easier to write and understand, and usually
also gives better performance. Furthermore, assume that you would have
more columns to set, like an average price, min price etc. In this case,
you would have to have several correlated subqueries, but the FROM
solution is very extensible in this regard.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

Friday, March 9, 2012

Group by statement problem

I am using the T-SQL code below to pull patient information. The code returns 86 rows, however, there are only 9 distinct account numbers. Why is the group by statement not grouping these together to only display the 9 distinct accounts and associated data?

select
srm.episodes.episode_type as Visit_Type,
srm.episodes.account_number as Account_Number,
srm.episodes.medrec_no as MRN,
dbo.PtMstr.PatientFullName,
left(srm.episodes.admission_date,11) as Admit_Date,
left(srm.episodes.episode_date,11) as Disch_Date,
dbo.PtMstr.Cases as Cases,
dbo.PtMstr.TotCharges,
srm.cdmab_base_info.abst_cmp_status as Abtract_Comp_Status,
srm.cdmab_base_info.adm_dx_adt as Admitting_Dx
,srm.event_types.event_type_code
from srm.cdmab_base_info inner join
srm.episodes on srm.episodes.episode_key = srm.cdmab_base_info.episode_key
inner join srm.event_history on srm.event_history.item_key = srm.episodes.episode_key
inner join srm.event_types on srm.event_types.event_type_key = srm.event_history.event_type_key
inner join dbo.PtMstr on dbo.PtMstr.AccountNumber = srm.episodes.account_number
where srm.cdmab_base_info.abst_cmp_status <> 'Y'
and srm.episodes.episode_date is not null
and srm.event_types.event_type_code <> 'ACOD'
AND srm.EPISODES.EPISODE_DATE Between @.StartDate and @.EndDate
AND srm.EPISODES.EPISODE_TYPE IN(@.VisitTypeCode)
Group By srm.episodes.account_number,
dbo.PtMstr.TotCharges,
srm.episodes.episode_type,
srm.episodes.medrec_no,
dbo.PtMstr.PatientFullName,
srm.episodes.admission_date,
srm.episodes.episode_date,
dbo.PtMstr.Cases,
srm.cdmab_base_info.abst_cmp_status,
srm.cdmab_base_info.adm_dx_adt,
srm.event_types.event_type_code

Use the following query..

select

srm.episodes.episode_type as Visit_Type,

srm.episodes.account_number as Account_Number,

srm.episodes.medrec_no as MRN,

dbo.PtMstr.PatientFullName,

left(srm.episodes.admission_date,11) as Admit_Date,

left(srm.episodes.episode_date,11) as Disch_Date,

dbo.PtMstr.Cases as Cases,

dbo.PtMstr.TotCharges,

srm.cdmab_base_info.abst_cmp_status as Abtract_Comp_Status,

srm.cdmab_base_info.adm_dx_adt as Admitting_Dx

,srm.event_types.event_type_code

from

srm.cdmab_base_info

inner join srm.episodes on srm.episodes.episode_key = srm.cdmab_base_info.episode_key

inner join srm.event_history on srm.event_history.item_key = srm.episodes.episode_key

inner join srm.event_types on srm.event_types.event_type_key = srm.event_history.event_type_key

inner join dbo.PtMstr on dbo.PtMstr.AccountNumber = srm.episodes.account_number

where

srm.cdmab_base_info.abst_cmp_status <> 'Y'

and srm.episodes.episode_date is not null

and srm.event_types.event_type_code <> 'ACOD'

AND srm.EPISODES.EPISODE_DATE Between @.StartDate and @.EndDate

AND srm.EPISODES.EPISODE_TYPE IN(@.VisitTypeCode)

Group By

srm.episodes.account_number,

dbo.PtMstr.TotCharges,

srm.episodes.episode_type,

srm.episodes.medrec_no,

dbo.PtMstr.PatientFullName,

left(srm.episodes.admission_date,11) as Admit_Date,

left(srm.episodes.episode_date,11) as Disch_Date,

dbo.PtMstr.Cases,

srm.cdmab_base_info.abst_cmp_status,

srm.cdmab_base_info.adm_dx_adt,

srm.event_types.event_type_code

|||

I had to remove the AS portion of the group by clause to get the code to work , however, it still returns 86 rows versus the expected 9 distinct rows.

|||

How you know there is only 9 distinct record. You only the get the number of rows as per the following query..& i didn't understand your requirement on your query(there is no group by funcations used).

select Distinct

srm.episodes.episode_type as Visit_Type,

srm.episodes.account_number as Account_Number,

srm.episodes.medrec_no as MRN,

dbo.PtMstr.PatientFullName,

left(srm.episodes.admission_date,11) as Admit_Date,

left(srm.episodes.episode_date,11) as Disch_Date,

dbo.PtMstr.Cases as Cases,

dbo.PtMstr.TotCharges,

srm.cdmab_base_info.abst_cmp_status as Abtract_Comp_Status,

srm.cdmab_base_info.adm_dx_adt as Admitting_Dx

,srm.event_types.event_type_code

from

srm.cdmab_base_info

inner join srm.episodes on srm.episodes.episode_key = srm.cdmab_base_info.episode_key

inner join srm.event_history on srm.event_history.item_key = srm.episodes.episode_key

inner join srm.event_types on srm.event_types.event_type_key = srm.event_history.event_type_key

inner join dbo.PtMstr on dbo.PtMstr.AccountNumber = srm.episodes.account_number

where

srm.cdmab_base_info.abst_cmp_status <> 'Y'

and srm.episodes.episode_date is not null

and srm.event_types.event_type_code <> 'ACOD'

AND srm.EPISODES.EPISODE_DATE Between @.StartDate and @.EndDate

AND srm.EPISODES.EPISODE_TYPE IN(@.VisitTypeCode)

|||

I appreciate you help. I ordered the data by account number and saw there were 9 distinct account numbers. I also noticed the srm.event_types.event_type_code field should not have been in this query; once I removed it, the code returned the expected 9 rows of data using either of the examples you provided. Thanks again for your assistance.

|||

You are grouping several additional columns after the account number.

If you just want the nine accounts listed, you'll need to just group on that column.

Then you can apply aggregates to get sums, etc. of the other data you desire.

GROUP BY Question

Hi,
I am struggling with a GROUP BY query that works fine until I add an
additional column to the select statement when i get duplicates, and I
believe the reason is that the query can not decide what column to aggregate
on. Not sure if this makes sense, but I was wodering if it is possible to
exclude a column from being aggregated.
The query is posted below, In essence if I remove the Club_Galas.MeetingName
from the select statement and the Club_Galas from the FROM statement the
query works OK and I get each individual athletes best result listed
(produces a ranking list based on all results). Would like to add info on
the occasion the record was produced but this causes atheltes names to be
listed multiple times
Any help appreciated
Niclas
Code below ->
Select Users.LastName + ', ' + Users.FirstName, MIN(Club_Results.Result)
as BestTime,Club_ExtUser.dob,Club_Galas.MeetingName
from Club_Results,Users,Club_Events,Club_ExtU
ser,Club_Galas
Where Club_ExtUser.UserID=users.userid
and
Users.UserID=Club_Results.UserID
AND
Club_Events.StrokeID=1
AND
Club_Events.DistanceID=1
AND
Club_Events.CourseID=1
AND
Club_Results.EventID=Club_Events.EventID
AND
Club_Events.GenderID=1
AND
Club_Results.GalaID=Club_Galas.GalaID
AND
Club_Results.ResultTypeID=1
Group by Users.LastName + ', ' +
Users.FirstName,Club_ExtUser.dob,Club_Galas.MeetingName
Order by BestTimeNiclas (lindblom_niclas@.hotmail.com) writes:
> I am struggling with a GROUP BY query that works fine until I add an
> additional column to the select statement when i get duplicates, and I
> believe the reason is that the query can not decide what column to
> aggregate on. Not sure if this makes sense, but I was wodering if it is
> possible to exclude a column from being aggregated.
> The query is posted below, In essence if I remove the
> CG.MeetingName from the select statement and the Club_Galas from
> the FROM statement the query works OK and I get each individual athletes
> best result listed (produces a ranking list based on all results). Would
> like to add info on the occasion the record was produced but this causes
> atheltes names to be listed multiple times
There are certainly solutions to your problem, but since you did not include
information how the tables are related, it's difficult to suggestion. So
standard suggestions follows:
Include
o CREATE TABLE statements for your tables (possibly simplified).
o INSERT statements with sample data that demonstrates the duplicates
you get.
o The desired output given the sample.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Niclas,
You seem to want one result row for each athlete, and in
that row, you want a MeetingName value (which you must
find in the Club_Galas table) as well. You are trying to find
the correct row of the Club_Galas table to look at from the
condition Club_Results.GalaID=Club_Galas.GalaID.
Evidently, for some athletes, more than one row in Club_Galas
satisfies this condition, and so you get multiple rows in your
result for each of these athletes - one row for each matching
row in Club_Galas. If you only want one row per athlete in
the result, you could select min(MeetingName) and remove
MeetingName from the GROUP BY clause. This will give
you just one MeetingName for each athlete - the one that
happens to be first in alphabetical order among the multiple
MeetingName values matching the athlete. It's also possible
that there is some specific MeetingName for each athlete,
but it is not what you are asking for. You are asking for
meeting names that appear in Club_Galas in a row with the
GalaID of a matching Club_Results row.
If you are getting multiple rows per athlete and those rows
are identical in every column, your problem may be that
you are not correctly modeling your scenario - maybe you
have no table that stores the relationship between GalaID
and MeetingName (if this is a 1-1 relationship) correctly,
meaning just once for each pair (GalaID,MeetingName).
A quick but terrible fix in this case would be to add DISTINCT
to the query - terrible, because it fixes the symptom, not
the underlying problem, which is that you are violating
the principle of storing a single fact ("this GalaID goes
with that MeetingName) in more than one place.
Steve Kass
Drew University
"Niclas" <lindblom_niclas@.hotmail.com> wrote in message
news:uHx0c0xkGHA.1344@.TK2MSFTNGP03.phx.gbl...
> Hi,
> I am struggling with a GROUP BY query that works fine until I add an
> additional column to the select statement when i get duplicates, and I
> believe the reason is that the query can not decide what column to
> aggregate on. Not sure if this makes sense, but I was wodering if it is
> possible to exclude a column from being aggregated.
> The query is posted below, In essence if I remove the
> Club_Galas.MeetingName from the select statement and the Club_Galas from
> the FROM statement the query works OK and I get each individual athletes
> best result listed (produces a ranking list based on all results). Would
> like to add info on the occasion the record was produced but this causes
> atheltes names to be listed multiple times
> Any help appreciated
> Niclas
> Code below ->
> Select Users.LastName + ', ' + Users.FirstName, MIN(Club_Results.Result)
> as BestTime,Club_ExtUser.dob,Club_Galas.MeetingName
> from Club_Results,Users,Club_Events,Club_ExtU
ser,Club_Galas
> Where Club_ExtUser.UserID=users.userid
> and
> Users.UserID=Club_Results.UserID
> AND
> Club_Events.StrokeID=1
> AND
> Club_Events.DistanceID=1
> AND
> Club_Events.CourseID=1
> AND
> Club_Results.EventID=Club_Events.EventID
> AND
> Club_Events.GenderID=1
> AND
> Club_Results.GalaID=Club_Galas.GalaID
> AND
> Club_Results.ResultTypeID=1
> Group by Users.LastName + ', ' +
> Users.FirstName,Club_ExtUser.dob,Club_Galas.MeetingName
> Order by BestTime
>|||I tried to remove the MeetingName from the GROUP BY CLAUSE, but this
generates the error message Column 'Club_Galas.MeetingName' is invalid in
the select list because it is not contained in either an aggregate function
or the GROUP BY clause.
The Club_Galas Table, the GalaID is the primary key and has a column called
MeetingName, there is only a single GalaID associated with each MeetingName,
So not sure what you refer to with the Underlaying problem
I will try to provide some more info about the desired result and table
relations
Niclas
"Steve Kass" <skass@.drew.edu> wrote in message
news:%23QGwnx0kGHA.4816@.TK2MSFTNGP05.phx.gbl...
> Niclas,
> You seem to want one result row for each athlete, and in
> that row, you want a MeetingName value (which you must
> find in the Club_Galas table) as well. You are trying to find
> the correct row of the Club_Galas table to look at from the
> condition Club_Results.GalaID=Club_Galas.GalaID.
> Evidently, for some athletes, more than one row in Club_Galas
> satisfies this condition, and so you get multiple rows in your
> result for each of these athletes - one row for each matching
> row in Club_Galas. If you only want one row per athlete in
> the result, you could select min(MeetingName) and remove
> MeetingName from the GROUP BY clause. This will give
> you just one MeetingName for each athlete - the one that
> happens to be first in alphabetical order among the multiple
> MeetingName values matching the athlete. It's also possible
> that there is some specific MeetingName for each athlete,
> but it is not what you are asking for. You are asking for
> meeting names that appear in Club_Galas in a row with the
> GalaID of a matching Club_Results row.
> If you are getting multiple rows per athlete and those rows
> are identical in every column, your problem may be that
> you are not correctly modeling your scenario - maybe you
> have no table that stores the relationship between GalaID
> and MeetingName (if this is a 1-1 relationship) correctly,
> meaning just once for each pair (GalaID,MeetingName).
> A quick but terrible fix in this case would be to add DISTINCT
> to the query - terrible, because it fixes the symptom, not
> the underlying problem, which is that you are violating
> the principle of storing a single fact ("this GalaID goes
> with that MeetingName) in more than one place.
> Steve Kass
> Drew University
> "Niclas" <lindblom_niclas@.hotmail.com> wrote in message
> news:uHx0c0xkGHA.1344@.TK2MSFTNGP03.phx.gbl...
>|||Erland, See some further info below. I hope this clarifies my objectives.
Let me know if further info is required
The results table contains one entry per recorded time per Athlete (UserID)
where the GalaID column contains a reference meeting/competition where the
result was recorded. I would like the query to produce a "Club Records" list
by selecting the fastest time each athlete has recorded in the database for
a particular Event and also display the MeetingName of the occasion where
the result was recorded
Club_Results
=============
ResultID int (PK)
UserID int
GalaID int
EventID int
FinalPosition int
Result DateTime
ResultTypeID int
AddedDate DateTime
ConfirmedDate DateTime
Relations
EventID (Club_Events - Club_Results)
GalaId (Club_Galas - Club_Results)
UserID (Users - Club_Results)
ResultTypeID (Club_ResultTypes - Club_Results)
Club_Galas
==============
GalaID int (PK)
ClubID int
LocationID int
GalaTypeID int
StartDate DateTime
FinishDate DateTime
MeetingName VarChar(50)
LayoutID int
CutoverDate DateTime
Relations
GalaID (Club_Galas - Club_Results)
ClubID (Club_Clubs - Club_Galas)
GalaTypeID (Club_GalaTypes-Club_Galas)
LocationID (Club_Locations - Club_Galas)
"Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
news:Xns97E74C12EBA7Yazorman@.127.0.0.1...
> Niclas (lindblom_niclas@.hotmail.com) writes:
> There are certainly solutions to your problem, but since you did not
> include
> information how the tables are related, it's difficult to suggestion. So
> standard suggestions follows:
> Include
> o CREATE TABLE statements for your tables (possibly simplified).
> o INSERT statements with sample data that demonstrates the duplicates
> you get.
> o The desired output given the sample.
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx|||Niclas (lindblom_niclas@.hotmail.com) writes:
> Erland, See some further info below. I hope this clarifies my objectives.
> Let me know if further info is required
> The results table contains one entry per recorded time per Athlete
> (UserID) where the GalaID column contains a reference
> meeting/competition where the result was recorded. I would like the
> query to produce a "Club Records" list by selecting the fastest time
> each athlete has recorded in the database for a particular Event and
> also display the MeetingName of the occasion where the result was
> recorded
Maybe something like:
SELECT G.MeetingName, U.UserName, E.EventName, R.Result
FROM Club_Results R
JOIN (SELECT UserID, minresult = MIN(Result)
FROM Club_Results
GROUP BY UserID) AS minR ON R.UserID = minR.UserID
AND R.Result = minR.Result
JOIN Club_Galas G ON R.GalaID = G.GalaID
JOIN Club_Events E ON R.EventID = E.EventID
But this is quite much of a wild guess from me. In my previous post
I suggested that you should post:
That suggestion still stands if you want any more useful reply.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Many thanks for your help Erland,
When running the query you suggested (understand that this is a best effort
guess), I get the error message:
The column prefix 'U' does not match with a table name or alias name used in
the query.
I have generated scripts in Enterprise Manager for the tables as requested
(Bottom of this post), not sure how I generate the INSERT statements you ask
for.
The desired result is a table listing each individual athletes lowest time
ranked from lowest to highest time value with a single entry per athlete who
has an occurence in the results table. With my initially posted query, I get
multiple matches per athlete and the query basically produces a list of all
results from lowest to highest time.
Table creation statement below
CREATE TABLE [dbo].[CLUB_Results] (
[ResultID] [int] IDENTITY (1, 1) NOT NULL ,
[UserID] [int] NOT NULL ,
[GalaID] [int] NOT NULL ,
[EventID] [int] NOT NULL ,
[FinalPosition] [int] NOT NULL ,
[Result] [datetime] NOT NULL ,
[ResultTypeID] [int] NOT NULL ,
[AddedDate] [datetime] NOT NULL ,
[ConfirmedDate] [datetime] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Users] (
[UserID] [int] IDENTITY (1, 1) NOT NULL ,
[Username] [nvarchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[FirstName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[LastName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[IsSuperUser] [bit] NOT NULL ,
[AffiliateId] [int] NULL ,
[Email] [nvarchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CLUB_Galas] (
[GalaID] [int] IDENTITY (1, 1) NOT NULL ,
[ClubID] [int] NOT NULL ,
[LocationID] [int] NOT NULL ,
[GalaTypeID] [int] NOT NULL ,
[StartDate] [datetime] NOT NULL ,
[FinishDate] [datetime] NOT NULL ,
[GalaName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[LayoutID] [int] NOT NULL ,
[CutoverDate] [datetime] NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[CLUB_Results] ADD
CONSTRAINT [DF_CLUB_Results_FinalPosition] DEFAULT (0) FOR [FinalPosition],
CONSTRAINT [DF_CLUB_Results_ConfirmedDate] DEFAULT ('1900/01/01 00:00:00')
FOR [ConfirmedDate],
CONSTRAINT [PK_CLUB_Results] PRIMARY KEY NONCLUSTERED
(
[ResultID]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Users] ADD
CONSTRAINT [DF_Users_IsSuperUser] DEFAULT (0) FOR [IsSuperUser],
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[UserID]
) ON [PRIMARY] ,
CONSTRAINT [IX_Users] UNIQUE NONCLUSTERED
(
[Username]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[CLUB_Galas] ADD
CONSTRAINT [PK_CLUB_Galas] PRIMARY KEY CLUSTERED
(
[GalaID]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[CLUB_Results] ADD
CONSTRAINT [FK_CLUB_Results_CLUB_Events] FOREIGN KEY
(
[EventID]
) REFERENCES [dbo].[CLUB_Events] (
[EventID]
),
CONSTRAINT [FK_CLUB_Results_CLUB_ResultTypes] FOREIGN KEY
(
[ResultTypeID]
) REFERENCES [dbo].[CLUB_ResultTypes] (
[ResultTypeID]
),
CONSTRAINT [FK_CLUB_Results_Users] FOREIGN KEY
(
[UserID]
) REFERENCES [dbo].[Users] (
[UserID]
)
GO
ALTER TABLE [dbo].[CLUB_Galas] ADD
CONSTRAINT [FK_CLUB_Galas_CLUB_Clubs] FOREIGN KEY
(
[ClubID]
) REFERENCES [dbo].[CLUB_Clubs] (
[ClubID]
),
CONSTRAINT [FK_CLUB_Galas_CLUB_GalaType] FOREIGN KEY
(
[GalaTypeID]
) REFERENCES [dbo].[CLUB_GalaType] (
[GalaTypeID]
),
CONSTRAINT [FK_CLUB_Galas_CLUB_Locations] FOREIGN KEY
(
[LocationID]
) REFERENCES [dbo].[CLUB_Locations] (
[LocationID]
)
GO
"Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
news:Xns97E8353B1CA5Yazorman@.127.0.0.1...
> Niclas (lindblom_niclas@.hotmail.com) writes:
> Maybe something like:
> SELECT G.MeetingName, U.UserName, E.EventName, R.Result
> FROM Club_Results R
> JOIN (SELECT UserID, minresult = MIN(Result)
> FROM Club_Results
> GROUP BY UserID) AS minR ON R.UserID = minR.UserID
> AND R.Result = minR.Result
> JOIN Club_Galas G ON R.GalaID = G.GalaID
> JOIN Club_Events E ON R.EventID = E.EventID
> But this is quite much of a wild guess from me. In my previous post
> I suggested that you should post:
>
> That suggestion still stands if you want any more useful reply.
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx|||Niclas (lindblom_niclas@.hotmail.com) writes:
> Many thanks for your help Erland,
> When running the query you suggested (understand that this is a best
> effort guess), I get the error message:
> The column prefix 'U' does not match with a table name or alias name
> used in the query.
Well, I suggested that you should post create table statements as well as
insert statements with sample data (that gives the problem with duplicates
with your original query) and the desired result for the sample. That makes
it very easy to develop a tested query.
Now you did not include that information, so I typed up an untested,
uncompiled query. Thus, there can be compilation errors in it. I gladly
assume that people who ask for help can sort out trivial errors like
missing aliases themselves.
In this post, you have included the tables, but not any data. So that is
your choice. But the thing is, the less effort you are prepared to put into
to help us, the less inclined I and other people are to take a stab at your
problem.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

Group by Query Insert the Results into Different Table

I am trying to do a select statement and input the result to a different table how can this be done in one step? Now I am just coping to excel and importing back in this is a real pain.

Select Trip, Destination, LeaveDate, LeaveTime, ReturnDate, ReturnTime, Comment, RescheduleDate from Trips

Group by Trip, Destination, LeaveDate, LeaveTime, ReturnDate, ReturnTime, Comment, RescheduleDate

Order by LeaveDate, LeaveTime, Trip

Here it is,

Code Snippet

--For One Time

Select Trip, Destination, LeaveDate, LeaveTime, ReturnDate, ReturnTime, Comment, RescheduleDate into TargetTable from Trips

Group by Trip, Destination, LeaveDate, LeaveTime, ReturnDate, ReturnTime, Comment, RescheduleDate

Order by LeaveDate, LeaveTime, Trip

--For Multiple Times

Create table Targettable

(

Trip int,

Destination varchar(10),

LeaveDate datetime,

LeaveTime varchar(10),

ReturnDate datetime,

ReturnTime varchar(10),

Comment text,

RescheduleDate datetime

)

Insert into Targettable

Select Trip, Destination, LeaveDate, LeaveTime, ReturnDate, ReturnTime, Comment, RescheduleDate from Trips

Group by Trip, Destination, LeaveDate, LeaveTime, ReturnDate, ReturnTime, Comment, RescheduleDate

Order by LeaveDate, LeaveTime, Trip

|||

Just create a table with fields that match those of your query. Then you can run

Code Snippet

INSERT INTO newTable

Select Trip, Destination, LeaveDate, LeaveTime, ReturnDate, ReturnTime, Comment, RescheduleDate from Trips

Group by Trip, Destination, LeaveDate, LeaveTime, ReturnDate, ReturnTime, Comment, RescheduleDate

Order by LeaveDate, LeaveTime, Trip

|||Sweet Thanks!!!

Group By problem

Hi,

I need help on constructing a SQL statement that will produce me the following result:

The table is:

TABLE sample
F1 F2
-- --
1 a
1 b
2 c
2 d

select F1, ? what group function?
from sample
group by F1

Result should be:
F1 xxx
-- ---
1 a,b
2 c,d

Thanks for all the help.select F1,F2 from sample group by f1 order by f1|||Originally posted by kharsa60
select F1,F2 from sample group by f1 order by f1

I don't think this is possible since F2 is not a group by function. I still tried it though and got the following error message:

Column 'sample.f2' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Any other suggestions?

Thanks.|||using pl/sql and or java you can do this quite easily. pseudo code;

rs1="select distinct(f1) from x order by f1"
while rs1.next
{
display rs1.f1
rs2="select f2 from x where f1=rs1.f1 order by f2"
while rs2.next
{
display rs2.f2
}
}|||I believe the only way you will get your output is with a cursor. This example is against PUBS database.
DECLARE @.pline varchar(200),
@.title_id tid,
@.cur_title tid,
@.au_id id

SET @.pline = ''

DECLARE out_cur CURSOR
READ_ONLY
FOR
SELECT title_id,
au_id
FROM titleauthor
ORDER BY
title_id

OPEN out_cur

FETCH NEXT FROM out_cur INTO @.title_id, @.au_id
SET @.cur_title= @.title_id

WHILE (@.@.fetch_status <> -1) BEGIN
IF (@.@.fetch_status <> -2) BEGIN
IF ( @.cur_title=@.title_id )
SET @.pline = @.pline + @.au_id + ', '
ELSE BEGIN
PRINT @.cur_title + ' : ' + SUBSTRING(@.pline,1,LEN(@.pline)-2)
SET @.pline = @.au_id + ', '
SET @.cur_title= @.title_id
END
END
FETCH NEXT FROM out_cur INTO @.title_id, @.au_id
END

CLOSE out_cur
DEALLOCATE out_cur
GO

The PL/SQL code that rhs98 showed can be done using ADO and VB,VBScript,Perl,etc. However I believe the output is not in the format that you want, it looks like the output would be a list.

F1
F2
F2
F1
F2
F2
F1
F2|||yeah ok, i see now, easily fixed though (that was only psuedo code btw). just don't use a println use a print; so the subsequent output stays on the same line.

or if that is a problem, you could just build up the output using a string or a buffer, and then display it before moving to the next loop.

I think this may be quicker to implement, but slightly slower than the pl/sql?|||guess it's really which way you know best; pl/sql or java...|||Considering that this is Microsoft SQL Server, PL/SQL is out and T-SQL is in.|||Thanks all. I see that there is no way of doing it via SQL statement. So I'll just going to do it in java then, since I am actually using java. I just thought I can do it with one SQL statement.

Thanks a lot.|||ooooooops :D
missed that one... :rolleyes:

Group By Problem

The following sql statement is giving error when i insert the line Group By...(to get the total amount of Job_id's):

SELECT Isnull(tbl1.Job_no, tbl2.Job_no) As Job_No, tbl1.Amount, tbl1.Entry_id
FROM tbl2 FULL OUTER JOIN tbl1
ON tbl1.colx = tbl2.coly
WHERE <Condition>
GROUP BY Isnull(tbl1.Job_no, tbl2.Job_no);

tbl1 and tbl2 have columns Job_no. But one has a null value if the other value other that null. So the statement above will list the job_no (combined from the two tables), the Amount and the Entry_ID. What i'm trying to arrive at is to add all amount on the same Job_no.

any comment will be greatly appreciated.

Thanks!

Quote:

Originally Posted by Merio

The following sql statement is giving error when i insert the line Group By...(to get the total amount of Job_id's):

SELECT Isnull(tbl1.Job_no, tbl2.Job_no) As Job_No, tbl1.Amount, tbl1.Entry_id
FROM tbl2 FULL OUTER JOIN tbl1
ON tbl1.colx = tbl2.coly
WHERE <Condition>
GROUP BY Isnull(tbl1.Job_no, tbl2.Job_no);

tbl1 and tbl2 have columns Job_no. But one has a null value if the other value other that null. So the statement above will list the job_no (combined from the two tables), the Amount and the Entry_ID. What i'm trying to arrive at is to add all amount on the same Job_no.

any comment will be greatly appreciated.

Thanks!


Instead of:
GROUP BY Isnull(tbl1.Job_no, tbl2.Job_no);
Try
GROUP BY Job_No.

But i belive that that work either,
What you might have to do is group by all tthe other fields
GROUP BY tbl1.Amount, tbl1.Entry_id|||

Quote:

Originally Posted by tezza98

Instead of:
GROUP BY Isnull(tbl1.Job_no, tbl2.Job_no);
Try
GROUP BY Job_No.

But i belive that that work either,
What you might have to do is group by all tthe other fields
GROUP BY tbl1.Amount, tbl1.Entry_id


------------

The problem was solved when i changed the first line with this:
SELECT Isnull(tbl1.Job_no, tbl2.Job_no) As Job_no, SUM(tbl1.amount) As Amount

I needed to put the SUM on tbl1.amount. - I thought that tbl1.amount would be totaled automatically when GROUP BY is used... I was wrong. :0

Thanks for your comment :)

Wednesday, March 7, 2012

Group by expiration date

Is there a way to get this down to one select statement and group it as such
in Reporting services?
select custnmbr,contnbr,enddate,Cast(total as Money) from svc00600
where enddate >=getdate() and enddate <=getdate()+30
order by enddate asc
select custnmbr,contnbr,enddate,Cast(total as Money) from svc00600
where enddate >=getdate()+30 and enddate <=getdate()+60
order by enddate asc
select custnmbr,contnbr,enddate,Cast(total as Money) from svc00600
where enddate >=getdate()+60 and enddate <=getdate()+120
order by enddate ascYou could try either of the options below. Then group on the new
psuedo-field DaysOut
select custnmbr,contnbr,enddate,Cast(total as Money), '30' as DaysOut
from svc00600
where enddate >=getdate() and enddate <=getdate()+30
UNION
select custnmbr,contnbr,enddate,Cast(total as Money), '60' as DaysOut
from svc00600
where enddate >=getdate()+30 and enddate <=getdate()+60
UNION
select custnmbr,contnbr,enddate,Cast(total as Money), '120' as DaysOut
from svc00600
where enddate >=getdate()+60 and enddate <=getdate()+120
order by enddate asc
SELECT custnmbr, contnbr, enddate, CAST(total AS MONEY),
'DAYSOUT' = CASE
WHEN enddate >= getdate() AND enddate <= DATEADD(DD,30,getdate())
THEN '30'
WHEN enddate >= DATEADD(DD,30,getdate()) AND enddate <=DATEADD(DD,60,getdate()) THEN '60'
WHEN enddate >= DATEADD(DD,60,getdate()) AND enddate <=DATEADD(DD,120,getdate()) THEN '120'
END
FROM svc00600
WHERE enddate >=getdate() AND enddate <= DATEADD(DD,120,getdate())
ORDER BY enddate ASC|||Awesome, thanks.
"Ches" wrote:
> You could try either of the options below. Then group on the new
> psuedo-field DaysOut
>
> select custnmbr,contnbr,enddate,Cast(total as Money), '30' as DaysOut
> from svc00600
> where enddate >=getdate() and enddate <=getdate()+30
> UNION
> select custnmbr,contnbr,enddate,Cast(total as Money), '60' as DaysOut
> from svc00600
> where enddate >=getdate()+30 and enddate <=getdate()+60
> UNION
> select custnmbr,contnbr,enddate,Cast(total as Money), '120' as DaysOut
> from svc00600
> where enddate >=getdate()+60 and enddate <=getdate()+120
> order by enddate asc
>
> SELECT custnmbr, contnbr, enddate, CAST(total AS MONEY),
> 'DAYSOUT' = CASE
> WHEN enddate >= getdate() AND enddate <= DATEADD(DD,30,getdate())
> THEN '30'
> WHEN enddate >= DATEADD(DD,30,getdate()) AND enddate <=> DATEADD(DD,60,getdate()) THEN '60'
> WHEN enddate >= DATEADD(DD,60,getdate()) AND enddate <=> DATEADD(DD,120,getdate()) THEN '120'
> END
> FROM svc00600
> WHERE enddate >=getdate() AND enddate <= DATEADD(DD,120,getdate())
> ORDER BY enddate ASC
>|||Be Careful--this query will possibly produce wrong results. If you do
<=getdate()+30 in the first group and >=getdate()+30 in the second, you will
potentially have a customer show up in both results. Your query should look
like:
select custnmbr,contnbr,enddate,Cast(total as Money), '30' as DaysOut
from svc00600
where enddate >=getdate() and enddate <=getdate()+30
UNION
select custnmbr,contnbr,enddate,Cast(total as Money), '60' as DaysOut
from svc00600
where enddate >getdate()+30 and enddate <=getdate()+60
UNION
select custnmbr,contnbr,enddate,Cast(total as Money), '120' as DaysOut
from svc00600
where enddate >getdate()+60 and enddate <=getdate()+120
order by enddate asc
Even still, this query will list account with less than 30, between 31 than
60 and between 61 and 120--not necessarily the accounts that are 30 days
overdue, 60 days over or 120 days over as I would assume you are interested
in.
Brian
"Jeff Metcalf" <JeffMetcalf@.discussions.microsoft.com> wrote in message
news:BBC3F268-B818-40FB-9D58-BDD8A2199F6E@.microsoft.com...
> Awesome, thanks.
> "Ches" wrote:
>> You could try either of the options below. Then group on the new
>> psuedo-field DaysOut
>>
>> select custnmbr,contnbr,enddate,Cast(total as Money), '30' as DaysOut
>> from svc00600
>> where enddate >=getdate() and enddate <=getdate()+30
>> UNION
>> select custnmbr,contnbr,enddate,Cast(total as Money), '60' as DaysOut
>> from svc00600
>> where enddate >=getdate()+30 and enddate <=getdate()+60
>> UNION
>> select custnmbr,contnbr,enddate,Cast(total as Money), '120' as DaysOut
>> from svc00600
>> where enddate >=getdate()+60 and enddate <=getdate()+120
>> order by enddate asc
>>
>> SELECT custnmbr, contnbr, enddate, CAST(total AS MONEY),
>> 'DAYSOUT' = CASE
>> WHEN enddate >= getdate() AND enddate <= DATEADD(DD,30,getdate())
>> THEN '30'
>> WHEN enddate >= DATEADD(DD,30,getdate()) AND enddate <=>> DATEADD(DD,60,getdate()) THEN '60'
>> WHEN enddate >= DATEADD(DD,60,getdate()) AND enddate <=>> DATEADD(DD,120,getdate()) THEN '120'
>> END
>> FROM svc00600
>> WHERE enddate >=getdate() AND enddate <= DATEADD(DD,120,getdate())
>> ORDER BY enddate ASC
>>|||Hey,
Querying GreatPlains data, huh?
You can avoid the union query with the following:
select custnmbr,contnbr,enddate datediff(dd, enddate, getdate()),
aging30 = case when datediff(dd, enddate, getdate())<=30 then Cast(total as
money) else 0 end ,
aging60 = case when datediff(dd, enddate, getdate())Between 31 and 60 then
cast(total as money) else 0 end
from SVC00600 order by enddate desc
and if you really wanted you could even sum and group reight in this query
Have you thought about using a matrix report and doing the grouping on the
report?
HS
"goodman" <goodman93@.hotmail.com> wrote in message
news:OcbuGbj3FHA.2144@.TK2MSFTNGP09.phx.gbl...
: Be Careful--this query will possibly produce wrong results. If you do
: <=getdate()+30 in the first group and >=getdate()+30 in the second, you
will
: potentially have a customer show up in both results. Your query should
look
: like:
:
: select custnmbr,contnbr,enddate,Cast(total as Money), '30' as DaysOut
: from svc00600
: where enddate >=getdate() and enddate <=getdate()+30
: UNION
: select custnmbr,contnbr,enddate,Cast(total as Money), '60' as DaysOut
: from svc00600
: where enddate >getdate()+30 and enddate <=getdate()+60
: UNION
: select custnmbr,contnbr,enddate,Cast(total as Money), '120' as DaysOut
: from svc00600
: where enddate >getdate()+60 and enddate <=getdate()+120
: order by enddate asc
:
: Even still, this query will list account with less than 30, between 31
than
: 60 and between 61 and 120--not necessarily the accounts that are 30 days
: overdue, 60 days over or 120 days over as I would assume you are
interested
: in.
:
: Brian
:
:
: "Jeff Metcalf" <JeffMetcalf@.discussions.microsoft.com> wrote in message
: news:BBC3F268-B818-40FB-9D58-BDD8A2199F6E@.microsoft.com...
: > Awesome, thanks.
: >
: > "Ches" wrote:
: >
: >> You could try either of the options below. Then group on the new
: >> psuedo-field DaysOut
: >>
: >>
: >> select custnmbr,contnbr,enddate,Cast(total as Money), '30' as DaysOut
: >> from svc00600
: >> where enddate >=getdate() and enddate <=getdate()+30
: >> UNION
: >> select custnmbr,contnbr,enddate,Cast(total as Money), '60' as DaysOut
: >> from svc00600
: >> where enddate >=getdate()+30 and enddate <=getdate()+60
: >> UNION
: >> select custnmbr,contnbr,enddate,Cast(total as Money), '120' as DaysOut
: >> from svc00600
: >> where enddate >=getdate()+60 and enddate <=getdate()+120
: >> order by enddate asc
: >>
: >>
: >>
: >> SELECT custnmbr, contnbr, enddate, CAST(total AS MONEY),
: >> 'DAYSOUT' = CASE
: >> WHEN enddate >= getdate() AND enddate <= DATEADD(DD,30,getdate())
: >> THEN '30'
: >> WHEN enddate >= DATEADD(DD,30,getdate()) AND enddate <=: >> DATEADD(DD,60,getdate()) THEN '60'
: >> WHEN enddate >= DATEADD(DD,60,getdate()) AND enddate <=: >> DATEADD(DD,120,getdate()) THEN '120'
: >> END
: >> FROM svc00600
: >> WHERE enddate >=getdate() AND enddate <= DATEADD(DD,120,getdate())
: >> ORDER BY enddate ASC
: >>
: >>
:
:

Sunday, February 26, 2012

GROUP BY CLAUSE

Greetings!

Why does the select statement must have the same non aggregated columns which are also part of the group by clause?

I have a feeling it's to do with the way the SQL Server database engine actually executes the query? i.e. the select part is the last thing the engine performs (after doing the joins and the filtering etc...).

Your help would be appreciated.

Hi..

Yes.. you are right.. SQL Server performs Select Part is almost last.. hence you have to provide the columns that are there in group by clause as non aggregate columns in the select..

Here is a quick reference to the Select Process in sequencial..

Code Snippet

Select
From
Join
On
Where
Group By
With {Cube | Rollup}
Having
Order By

Sequence

1. from <left table>
2. on <join condition>
3. <join type> join <right table>
4. where <where condition>
5. group by <fields list>
6. with {cube | rollup}
7. having <having condition>
8. Select
9. distinct
10. order by <field list>
11. <top spciancifications>

Hope this helps..

|||

MS already heard from you..

If you use SQL Server 2005, you can have other columns in your Select statement. Using OVER clause..

The query will look like this...

select *, Sum(Price) over (partition by orderId) from orders

Group by and Order By Problem

I have the following statement that is working just fine:

SQL = "select* from products GROUP BY name ORDER BY price"

I have many products with the same name but with different prices and I want to display unique records along with other information but I want to display the cheapest product first. It is displaying the first record in the table with that name but not the cheapest distinct record in the list of all distinct product names.

Not sure of the above makes sense so this is the kind of data in the table.

Name= Test1, Price= 25

Name= Test2, Price= 20

Name= Test1, Price= 15

Name= Test3, Price=30

When listing the products it will show the following order:

Test2, 20

Test1, 25

Test3, 30

However I want it to display:

Test1, 15

Test2, 25

Test3, 30

Thanks for any help.

Daniel

What version of SS are you working with?

In case of having same product with same price multiple times, then we need a tie breaker in order to make the solution deterministic.

select *

from dbo.product as a

where not exists (

select *

from dbo.product as b

where b.[name] = a.[name] and b.price < a.price

)

select *

from dbo.product as a

where price = (

select min(b.price)

from product as b

where b.[name] = a.[name]

)

select *

from dbo.product as a

where price = (

select top 1 b.price

from product as b

where b.[name] = a.[name]

order by b.price

)

-- 2005

with cte

as

(

select *, row_number() over(partition by [name] order by price) rn

from dbo.product

)

select *

from cte

where rn = 1

go

AMB

|||Just a kind reminder, the 2000 and 2005 solution may not return the same results.
Such as
Name= Test1, Price= 25
Name= Test2, Price= 20
Name= Test1, Price= 15
Name= Test3, Price=30
Name= Test1, Price=15

2000 Version return:

Test1,15
Test2,20
Test3,30
Test1,15

2005 version return:
Test1,15
Test2,20
Test3,30

To make two solutions equal, it needs add DISTINCT to outer select.

Such as:

select DISTINCT *

from dbo.product as a

where not exists (

select *

from dbo.product as b

where b.[name] = a.[name] and b.price < a.price

)


|||

You are right. I should have used dense_rank instead row_number or "distinct" as you mentioned. I would prefer to include a second column, like transaction_id, as the tie breaker.

AMB

Friday, February 24, 2012

Group by and Case Statements

Hi,
I have a query where I am using a case statement and a group by e.g.
Select Field1, Field2, Field3, Max(Field4),
CASE
WHEN <something> THEN ' '
WHEN <something> THEN 1
END as Field4
WHERE <something>
GROUP BY Field1, Field2, Field3, Field4
The problem I am having is the group by isn't using the value from
the Case Statement, it's not grouping the records correctly. Anyone
have any idea's why that would happen?
Thanks for the helpBy definition, the expressions in the GROUP BY clause reffer to the
columns from the table, not to the columns defined in the SELECT
clause. You probably need to use a subquery for this:
SELECT Field1, Field2, Field3, MAX(Field4), TheExpression as Field4
FROM (
SELECT Field1, Field2, Field3, Field4,
CASE
WHEN <something> THEN ' '
WHEN <something> THEN 1
END as TheExpression
FROM <your table>
WHERE <something>
) x
GROUP BY Field1, Field2, Field3, TheExpression
Razvan|||Thanks, that's what I figured. I was hoping there was a more eligant
way around that.
Thanks|||Simply copy the same CASE expression used in the SELECT list into the
GROUP BY:
Select Field1, Field2, Field3, Max(Field4),
CASE
WHEN <something> THEN ' '
WHEN <something> THEN 1
END as Field4
WHERE <something>
GROUP BY Field1, Field2, Field3,
CASE
WHEN <something> THEN ' '
WHEN <something> THEN 1
END
Roy Harvey
Beacon Falls, CT
On 3 May 2006 09:25:44 -0700, "Red2" <sdibello@.gmail.com> wrote:

>Hi,
> I have a query where I am using a case statement and a group by e.g.
> Select Field1, Field2, Field3, Max(Field4),
> CASE
> WHEN <something> THEN ' '
> WHEN <something> THEN 1
> END as Field4
> WHERE <something>
> GROUP BY Field1, Field2, Field3, Field4
> The problem I am having is the group by isn't using the value from
>the Case Statement, it's not grouping the records correctly. Anyone
>have any idea's why that would happen?
>Thanks for the help|||Red2 wrote:
> Hi,
> I have a query where I am using a case statement and a group by e.g.
> Select Field1, Field2, Field3, Max(Field4),
> CASE
> WHEN <something> THEN ' '
> WHEN <something> THEN 1
> END as Field4
> WHERE <something>
> GROUP BY Field1, Field2, Field3, Field4
> The problem I am having is the group by isn't using the value from
> the Case Statement, it's not grouping the records correctly. Anyone
> have any idea's why that would happen?
--BEGIN PGP SIGNED MESSAGE--
Hash: SHA1
It'd be better if you showed the actual query. Your example has a
Max(Field4) and the CASE expression is labeled as Field4. If the GROUP
BY clause has Field4 is will be grouping the Field4 in the Max()
function. Obviously, not what you want to do. Is this a misnomer or
are you really using the same column in the Max() function and as the
CASE expression's name?
If you want to GROUP BY the result of a CASE expression you have to
include the CASE expression in the GROUP BY clause:
GROUP BY field1, field2, field3, CASE WHEN <something> THEN X ELSE Y END
--
MGFoster:::mgf00 <at> earthlink <decimal-point> net
Oakland, CA (USA)
--BEGIN PGP SIGNATURE--
Version: PGP for Personal Privacy 5.0
Charset: noconv
iQA/AwUBRFkUgYechKqOuFEgEQLZ2ACdHDbb0StLG/MEkaOpME4KfeDYTfcAn1I2
EEZOhQ/brevVe0gSJNujPhER
=aD2k
--END PGP SIGNATURE--

GROUP BY alias...possible?

Hello,
I have a statement as follows:
SELECT field1, field2, {expression} as calc1
FROM table1
GROUP BY field1, calc1
The absolutely critical thing to this statement is that I need to group
by calc1, but I get an 'Invalid Column Name' error. However, to get the
results I need I have to do a calculation as the data required is not
available in that form in the table, and I also have to be able to
group by it too. I'm sure someone must have come across this problem
and found a workaround?Well, one way to do this is to use calculation in the group by:
select
col1-col2 as Diff,
col3
from
table1
group by
(col1-col2),
col3
Is this good enough or you really need to use the same name?
MC
<champ.supernova@.gmail.com> wrote in message
news:1133343294.033508.241990@.o13g2000cwo.googlegroups.com...
> Hello,
> I have a statement as follows:
> SELECT field1, field2, {expression} as calc1
> FROM table1
> GROUP BY field1, calc1
> The absolutely critical thing to this statement is that I need to group
> by calc1, but I get an 'Invalid Column Name' error. However, to get the
> results I need I have to do a calculation as the data required is not
> available in that form in the table, and I also have to be able to
> group by it too. I'm sure someone must have come across this problem
> and found a workaround?
>|||champ.supernova@.gmail.com wrote on 30 Nov 2005 01:34:54 -0800:

> Hello,
> I have a statement as follows:
> SELECT field1, field2, {expression} as calc1
> FROM table1
> GROUP BY field1, calc1
> The absolutely critical thing to this statement is that I need to group
> by calc1, but I get an 'Invalid Column Name' error. However, to get the
> results I need I have to do a calculation as the data required is not
> available in that form in the table, and I also have to be able to
> group by it too. I'm sure someone must have come across this problem
> and found a workaround?
You can use {expression} in the group by instead of calc1 (just copy the
expression from the select), or use a subquery, or use DISTINCT. However,
you've still got a problem - you can't have field2 in your select list if
you're not grouping by it. If you don't need that field, remove it from the
select, if you do then add it to your group by. Assuming that you don't want
it, here's a couple of ideas:
SELECT field1, {expression} as calc1
FROM table1
GROUP BY field1, {expression}
SELECT DISTINCT field1, {expression} as calc1
FROM table1
SELECT field1, calc1
FROM
(SELECT field1, {expression} as calc1
FROM table1) As A
GROUP BY field1, calc1
SELECT DISTINCT field1, calc1
FROM
(SELECT field1, {expression} as calc1
FROM table1) As A
Dan|||Thanks guys, MC's answer solved it. Much obliged.

GROUP BY / HAVING clauses problem

I'm trying to set up my adhoc query to return just one single record,
which is aliased as 'foreign' in my sql statement (which is just the
total amount of foreign overseas orders for just one day. All
Sale_Type_Ids over 2 [integer datatype] are foreign orders):
SELECT SUM(CASE WHEN Orders.Sale_Type_Id > 2 THEN
Orders.Sale_Type_Id ELSE NULL END) AS foreign
FROM Orders INNER JOIN
Processing ON Orders.ID = Processing.Order_ID
WHERE (Processing.Orderdate = '20050915') AND (Processing.status =
1)
GROUP BY CASE WHEN Orders.Sale_Type_Id > 2 THEN Orders.Sale_Type_Id
ELSE NULL END
HAVING (SUM(CASE WHEN Orders.Sale_Type_Id > 2 THEN
Orders.Sale_Type_Id ELSE NULL END) >= 0)
..but my resultset is returning two records. If I remove the HAVING
clause, it will return three records, with one being blank.
?
.netsportsIf I understand correctly, your GROUP BY is on:
All Orders.Sale_Type_ID greater than 2
NULL
So, without the HAVING I would expect one row returned for each Sale_Type_ID
> 2 and one for all the rest which become NULL. Do you have two ID>2 within
the rows covered by your WHERE clause.
The HAVING apparently is able to prune out the NULL value.
Perhaps all you wanted was:
SELECT SUM(Orders.Sale_Type_Id) AS foreign
FROM Orders INNER JOIN
Processing ON Orders.ID = Processing.Order_ID
WHERE (Processing.Orderdate = '20050915') AND (Processing.status =1) AND
Orders.Sale_Type_ID > 2
RLF
".Net Sports" <ballz2wall@.cox.net> wrote in message
news:1127848228.326875.56120@.g49g2000cwa.googlegroups.com...
> I'm trying to set up my adhoc query to return just one single record,
> which is aliased as 'foreign' in my sql statement (which is just the
> total amount of foreign overseas orders for just one day. All
> Sale_Type_Ids over 2 [integer datatype] are foreign orders):
> SELECT SUM(CASE WHEN Orders.Sale_Type_Id > 2 THEN
> Orders.Sale_Type_Id ELSE NULL END) AS foreign
> FROM Orders INNER JOIN
> Processing ON Orders.ID = Processing.Order_ID
> WHERE (Processing.Orderdate = '20050915') AND (Processing.status =
> 1)
> GROUP BY CASE WHEN Orders.Sale_Type_Id > 2 THEN Orders.Sale_Type_Id
> ELSE NULL END
> HAVING (SUM(CASE WHEN Orders.Sale_Type_Id > 2 THEN
> Orders.Sale_Type_Id ELSE NULL END) >= 0)
> ..but my resultset is returning two records. If I remove the HAVING
> clause, it will return three records, with one being blank.
> ?
> .netsports
>|||If you only want a single row then remove the GROUP BY clause. GROUP BY
returns one row per group.
David Portas
SQL Server MVP
--|||Thanks. Looks like i'm getting the desired resultset. This sql
statement was sort of a permutation of an extensive one that would
bring back multiple records, but yes, I was starting to think if the
Group By was really necessary.|||I'm inferring your schema to be something like this:
CREATE TABLE Orders
(
ID INT PRIMARY KEY ?
, Sale_Type_Id INT
, Order_Total MONEY ?maybe
)
CREATE TABLE Processing
(
OrderID INT REFERENCES Orders(OrderID)
, Orderdate DATETIME
, Status INT
)
Your question sounds like you're either trying to find a count of
orders, or total amount purchased (which is why I made up that
ordertotal field). If either of those are what you're looking for,
there are much syntactically simpler solutions.
e.g.
SELECT COUNT(*) CountOfForeignOrders
, SUM(Order_Total) TotalOfForeignOrders
FROM Orders
WHERE Sale_Type_Id > 2 AND EXISTS(SELECT * FROM Processing WHERE
OrderID = Orders.ID AND OrderDate = '20050915' AND Status = 1)
When performing aggregates with join clauses, it's possible to
aggregate the same value more than once if a join causes the same row
to appear multiple times in the resultset. GROUP BY and HAVING aren't
necessary unless you're selecting your data based on your aggregate,
and if you'd return multiple aggregate sets.
-Alan