Showing posts with label joining. Show all posts
Showing posts with label joining. Show all posts

Tuesday, March 27, 2012

Concat Null Yields Null Woes..

I have a bunch of views that concat fileds, some of which allow nulls
so I am using the isNull function when joining them. I dont want to
have to do this, I want to set the database so that concat null does
not yield null for all views and procedures.
How do I do this this in EM ?
I read and tried a bunch of stuff on this but nothings worked so far.
Please dont reply telling me to use the concat null yields null
setting - I think I know what needs doing - but I dont know "How" to do
it!
Thanks.Thats because QA uses ODBC connection and by default its set CONCAT....NULL
to ON. and it overrides the database setting that you might have given.
you will have to explicitely state it in the connection
SET CONCAT_NULL_YEILDS_NULL OFF.
And your view is just a query given a name. So it will take the connection
setting. There is no point in setting that flag during view creation. You
will have to set it during access.
Hope this helps.
--
-Omnibuzz (The SQL GC)
http://omnibuzz-sql.blogspot.com/|||You can set CONCAT_NULL_YIELDS_NULL at the database level with ALTER
DATABASE or at the server level using the 'user options' of sp_configure.
However, it is unlikely that this will provide the behavior you want because
OLE DB and ODBC APIs explicitly SET CONCAT_NULL_YIELDS_NULL ON when
connecting to provide ANSI standard compliance by default. SET
CONCAT_NULL_YIELDS_NULL OFF needs to be explicitly set by each OLEDB/ODBC
client application using the view.
The best approach to ensure consistent results is to specify ISNULL or
COALESCE in the view expression. One can also argue that concatenation is
better handled in the client application rather that the server side.
Note that CONCAT_NULL_YIELDS_NULL ON is required to take advantage of
features like indexes on computed columns and views.
Hope this helps.
Dan Guzman
SQL Server MVP
"hals_left" <cc900630@.ntu.ac.uk> wrote in message
news:1150110841.616205.127710@.c74g2000cwc.googlegroups.com...
>I have a bunch of views that concat fileds, some of which allow nulls
> so I am using the isNull function when joining them. I dont want to
> have to do this, I want to set the database so that concat null does
> not yield null for all views and procedures.
> How do I do this this in EM ?
> I read and tried a bunch of stuff on this but nothings worked so far.
> Please dont reply telling me to use the concat null yields null
> setting - I think I know what needs doing - but I dont know "How" to do
> it!
> Thanks.
>|||Thank you both.
Dan Guzman wrote:
> You can set CONCAT_NULL_YIELDS_NULL at the database level with ALTER
> DATABASE or at the server level using the 'user options' of sp_configure.
> However, it is unlikely that this will provide the behavior you want becau
se
> OLE DB and ODBC APIs explicitly SET CONCAT_NULL_YIELDS_NULL ON when
> connecting to provide ANSI standard compliance by default. SET
> CONCAT_NULL_YIELDS_NULL OFF needs to be explicitly set by each OLEDB/ODBC
> client application using the view.
> The best approach to ensure consistent results is to specify ISNULL or
> COALESCE in the view expression. One can also argue that concatenation is
> better handled in the client application rather that the server side.
> Note that CONCAT_NULL_YIELDS_NULL ON is required to take advantage of
> features like indexes on computed columns and views.
> --
> Hope this helps.
> Dan Guzman
> SQL Server MVP
> "hals_left" <cc900630@.ntu.ac.uk> wrote in message
> news:1150110841.616205.127710@.c74g2000cwc.googlegroups.com...|||>> I have a bunch of views that concat fields [sic], some of which allow NULLs so
I am using the ISNULL() function when joining them. I dont want to have to
do this, I want to set the database so that concat NULL does not yield NUL
L for all views and pr
ocedures. <<
Oh, you want to write your own language and not bother with SQL! This
behavior is one of many reasons that columns are not anything like
fields and why I jump on newbies to actually read a book about the
language before they start coding.
Nobody should be so irresponsible as to give you that advice. Your
code would not port, would not work properly, etc. what needs doing
is a bit more education on your part instead of looking for kludges to
save yourself some typing. Also, why aren't you using QA or a code
editor instead of EM?
SQL programmers think of the schema as a whole. The first place to
look is the DDL and the Data Dictionary (which you probably do not
have, if you have that many NULLs). Which of these columns really
should be blanks, empty strings or other defaults and not NULL-able at
all? I will bet most of them, based on two decades of cleaning up
SQL.
You will find that most bad DML are kludges made in response to bad
DDL.|||And I thought the iea of newsgrouops was to help ....
Thanks for your advice, but with respect, this isnt the theory of
doing databases this is databases - real ones for real businesses with
real (small) budgets and real tight deadlines and working pretty well
considering ...

> Oh, you want to write your own language and not bother with SQL!
Not particularly, but yeah Im happy to break the rules now and then,
for good reasons of course, its worked so far nayway...
columns are not anything like fields
True, but that doesnt really get in the way of business, we focus on
the things that matter...

>why I jump on newbies to actually read a book about the language before they start
coding
Books suit some learning types, not mine, took the test, I know how I
learn best..
Also, why aren't you using QA or a code editor instead of EM?
EM is easier and faster (for me) to use.

>Data Dictionary (which you probably do not have, if you have that many NULLs).[/col
or]
Yeah I follow agile principles - My code is the documentation!
>Which of these columns really should be blanks, empty strings or other defaults and
not NULL-able at all?
Maybe a few should be empty strings instread

> You will find that most bad DML are kludges made in response to bad DDL.
You could say the same about requirements and design
You could say the same about feasibiliy and requirements
Sometimes it pays to jump in and build the damn system and deal with
the tweaks afterwards,

>based on two decades of cleaning up SQL.
No amount of experience gives anyone right to post unhelpfull,
self-indulgent replies ...
--CELKO-- wrote:
procedures. <<
> Oh, you want to write your own language and not bother with SQL! This
> behavior is one of many reasons that columns are not anything like
> fields and why I jump on newbies to actually read a book about the
> language before they start coding.
>
> Nobody should be so irresponsible as to give you that advice. Your
> code would not port, would not work properly, etc. what needs doing
> is a bit more education on your part instead of looking for kludges to
> save yourself some typing. Also, why aren't you using QA or a code
> editor instead of EM?
> SQL programmers think of the schema as a whole. The first place to
> look is the DDL and the Data Dictionary (which you probably do not
> have, if you have that many NULLs). Which of these columns really
> should be blanks, empty strings or other defaults and not NULL-able at
> all? I will bet most of them, based on two decades of cleaning up
> SQL.
> You will find that most bad DML are kludges made in response to bad
> DDL.|||>> And I thought the idea of newsgroups was to help ... <<
But there is an assumption that someone wants real help and not just a
kludge.
Wasn' t that what the accountants at Enron said -- this isn't about the
theory of accounting, etc. Why do you think a small budgets means
that you cannot do things right? The guy with the small budget is the
one who can least afford errors.
Correctness and maintainability are far more important than raw coding
speed. Hey, if it does not have to be right, the answer is always 42!
But later on you admit that you do not like to read things, so how do
you know what the rules are to make an informed decision about breaking
them? And somehow, you are always find a "good reason", such as your
dislike of typing in this thread :) And it probably has not worked,
but you do not know it yet.
Yes, it does matter. Do you go to a doctor who does not know the basic
concepts of his trade? Forget the fancy stuff, just the basic
concepts. It takes SIX years to become a Union Journeyman Carpenter in
New York State, but a kid with a few ws of MS Certificate cramming
thinks he is a programmer.
You might want to look at this:
http://www.apa.org/journals/psp/psp7761121.html
It is an article in the Journal of Personality and Social Psychology
entitled "Unskilled and Unaware of It: How Difficulties in Recognizing
One's Own Incompetence Lead to Inflated Self-Assessments"; the premise
is that people tend to hold overly favorable views of their abilities
in many social and intellectual domains. The authors suggest that this
overestimation occurs, in part, because people who are unskilled in
these domains suffer a dual burden: Not only do these people reach
erroneous conclusions and make unfortunate choices, but their
incompetence robs them of the metacognitive ability to realize it.
They tested some of the skills needed for programming.
The idea of learning, say, Normalization by "Trial & Error", looking at
training films or reading & writing a few thousand line of code seems a
bit .. expensive :)
This is the excuse that lazy and incompetent programmers use to cover
the fact that they do not know what they are doing. Does your code
include the external sources that provide data to your system? Do you
have a DFD for the system as a whole? I hope your end users are all SQL
programmers with about 15-20 years experience as well as domain experts
who can read that code when they need to use that system.
Do you know why you need a data dictionary? Do you even know what it
is? This is like an apprenice carpenter saying that "My house wiring
is the blueprint!"
One of my god-children and her husband have a small consulting company
in Atlanta. They are currently bidding on a job where the former
"Agile/XP/Cowboy Coder" decided that documentation is "just sooo anal!"
and was busy too refactoring code to bother with it. After a year of
"agile principles", the project is a failure. In fact, most Agile/XP
projects fail.
Since you do not llike to read, you might not have heard of the C3
(Chrysler Comprehensive Compensation) project. It was where XP began.
It was a payroll system that was to get around Y2K problems. It
started in 1996 and was cancelled in 2000 February. It had 1/3 of the
requirements originally promised and was so unusable that it was
scrapped by the end of 2000 and disappeared by 2002.
Maybe. Let's look at the specs and the data dictionary. Wait, yoyu
don't have those things.
You could say the same about requirements and design <<
We do say that! In fact, we measured the cost of errors in
requirements and design in the 1970's and later. This is one of the
major points of software engineering. In the classic DoD-2167 model
the total addition cost increased by about 10x at each step.
30 years of research disagrees with you. Check out the SEI, DoD, IBM,
any university research project on TCO of software, Barry Boehm and the
aerospace industry, etc. Did you see the piece on PBS on the levies
in New Orleans tonight? The Army Corp of Engineers They also built the
damn system and dealt with the tweaks afterwards.
What part of free speech and open forums confuses you? And when you
get over that hump of invincible igorance, you might find that you got
a lot of good advice instead of a kludge.

Computing several columns for each row in source table and joining to get result

I have come across this several times now, and I cannot figure out how to do
it better. Say I have a simple table called SourceTable:
DECLARE @.sourceTable TABLE
(
data1 INT,
data2 INT,
data3 INT,
data4 INT
)
I need to create a table (view, tv function, etc.) that looks something like
DECLARE @.resultTable TABLE
(
data1 INT,
data2 INT,
data3 INT,
data4 INT,
date1 SMALLDATETIME,
date2 SMALLDATETIME
)
where date1 and date2 are calculated (with functions) using data1...data4
from the same row plus another parameter supplied by the user. So you see
what I want is so simple: For each row in @.sourceTable, evaluate a
table-valued function getDates() that returns a single row containing date1
and date2, and join the result to produce @.resultTable. However, I can't
figure out any syntax to do this straightforwardly.
In some cases where date2 depends on date1, I can use nested queries, so I
can do something like
SELECT
data1,
data2,
data3,
data4,
date1,
date2 = getDate2(@.userInput, date1, data3, data4)
FROM (
SELECT
data1,
data2,
data3,
data4,
date1 = getDate1(@.userInput, data1, data2)
FROM
@.sourceTable
) T1
But recently, I have had several problems where it would be more efficient
and maintainable if I could return both date1 and date2 from a table-valued
function as a single row with two columns. This is because the relationship
between date1 and date2 is more complicated and they can't just be computed
sequentially. My first attempt was to write a TV function that basically
was
CREATE FUNCTION getDates (@.userInput INT, @.data1 INT, @.data2 INT, @.data3
INT, @.data4 INT)
RETURNS @.dates TABLE (date1 SMALLDATETIME, date2 SMALLDATETIME) AS
BEGIN
DECLARE @.date1 SMALLDATETIME
SET @.date1 = getDate1(@.userInput, @.data1, @.data2)
DECLARE @.date2 SMALLDATETIME
SET @.date2 = getDate2(@.userInput, @.data3, @.data4)
IF (@.date1 < @.date2)
SET @.date1 = getDate1(@.date2, @.data1, @.data2)
INSERT INTO @.dates
SELECT @.date1, @.date2
RETURN
END
I tried to join the function with the source table to get my result table as
follows:
SELECT
ST.data1,
ST.data2,
ST.data3,
ST.data4,
D.date1,
D.date2
FROM @.sourceTable ST
INNER JOIN getDates(
@.userInput,
ST.data1,
ST.data2,
ST.data3,
ST.data4) D
but SQL Server always complains when it reaches the 'ST' in the second
argument of getDates(), because apparently ST is not available in that
context. I tried using a cursor to evaluate getDates() for each row in
@.sourceTable and join the result to produce @.resultTable, but something was
just wrong and the query batch would never finish executing in query
analyzer. (I debugged and found that the cursor was implemented properly,
it was just extremely slow or was hanging in QA.) For now, I am using a
several-level-deep nested query that performs the logic of of my getDates()
function. Each query level performs one calculation or condition on one of
the two dates, and the rest of the columns just get carried along. For
example:
SELECT
data1,
data2,
data3,
data4,
date1 = CASE WHEN (date1 < date2)
THEN getDate1(date2, data1, data2)
ELSE date1
END,
date2
FROM (
SELECT
data1,
data2,
data3,
data4,
date1,
date2 = getDate2(@.userInput, data3, data4)
FROM (
SELECT
data1,
data2,
data3,
data4,
date1 = getDate1(@.userInput, data1, data2)
FROM
@.sourceTable
) RT1
) RT2
The query is actually a few levels deeper because I have to calculate other
things based on date1, and there are many more columns. This is horrible in
terms of readability and maintanability because the logic is distributed
throughout each level of the query, and I have to repeat all the columns at
each level. If I could return more than one column from a correlated
subquery, I would be fine, but I don't believe this is possible. Can
someone please help?Well, at least I know it wasn't just me. Thanks!
"Steve Kass" <skass@.drew.edu> wrote in message
news:%23hvbu$gEGHA.2012@.TK2MSFTNGP14.phx.gbl...
> Dustbort,
> SQL Server 2000 and earlier do not support "correlated joins",
> which is what you are trying to write. In your example, the
> right-hand table is a table-valued function that is a different
> table for each row of the left-hand table.
> In SQL Server 2005, this can be done with the new
> APPLY operator. In 2000, there is no easy way,
> though it's possible that there is an easier way to solve
> your specific problem.
> Steve Kass
> Drew University
>
> dustbort wrote:
>

Thursday, March 8, 2012

Complex View creation question

I need to create a cross-database view (same server) in a master database.
The databases I'm joining in the view are listed in a table in that master.
I'd like for the view to automatically include new databases whose names are
added to that table in the master. How would I go about doing this? I'm no
t
familiar with dynamic sql... TIA.Views aren't going to have dynamic SQL in them, and I wouldn't really
recommend a multi-line table user-defined function even though you could
probably accomplish what you want by using dynamic SQL in it.
I would recommend a hook in your application/middle-tier (optimally) or a
trigger on that master table (less optimal) that would ALTER the view to
include all the existing databases in your master table whenever the list of
databases changes. Just create the ALTER VIEW statement based on the list
from the master table. If done from the app, you have many ways to do this;
if from a trigger, you'd create the SQL string via a cursor or a funky
SELECT statement and then execute it via EXEC (dynamic SQL).
The things to consider in this scenario would be: what impact does changing
the view have on the live system? how frequently does this change? does
the user adding/deleting records in the master table have permissions to
alter the view?
Mike
"William Sullivan" <WilliamSullivan@.discussions.microsoft.com> wrote in
message news:AD0E4C8D-1983-4003-B8FE-09D0222548F4@.microsoft.com...
>I need to create a cross-database view (same server) in a master database.
> The databases I'm joining in the view are listed in a table in that
> master.
> I'd like for the view to automatically include new databases whose names
> are
> added to that table in the master. How would I go about doing this? I'm
> not
> familiar with dynamic sql... TIA.

Saturday, February 25, 2012

Complex Query

Hello,
I am having trouble in getting the expected results. I have two tables as below. I need Idno,transdt,cd,cycdt,amt from joining two tables. The criteria is that if the transdt greater than same month of cycdt then we need get the next month cycdt and corresponding amount for that, if it is less than or equal to same months cycdt then get the same months cycdt and amt. Cd is dummy field which can be anything. I am using sqlserver 8.0

table1
idno,trandt,cd
12345,04/15/2005,cd1
12345,04/15/2005,cd2
12345,04/22/2005,cd3
12345,07/03/2005,cd4
12345,09/10/2005,cd5
3421,03/05/2005,cd6
3421,05/06/2005,cd7
3421,07/04/2005,cd8
3421,07/15/2005,cd9
3421,09/15/2005,cd10

idno,cycdt,amt
12345,02/10/2005,15.43
12345,03/13/2005,40.84
12345,04/18/2005,10.10
12345,05/24/2005,13.00
12345,06/16/2005,20.89
12345,07/18/2005,12.12
12345,08/17/2005,10.89
12345,09/17/2005,12.87
12345,10/16/2005,13.89
3421,05/10/2005,15.00
3421,06/11/2005,20.00
3421,07/11/2005,14.15
3421,08/12/2005,15.54

Expected result.
12345,04/15/2005,cd1,04/18/2005,10.10
12345,04/15/2005,cd2,04/18/2005,10.10
12345,04/22/2005,cd3,05/24/2005,13.00
12345,07/03/2005,cd4,07/18/2005,12.12
12345,09/10/2005,cd5,09/17/2005,12.87
3421,05/06/2005,cd7,05/10/2005,15.00
3421,07/04/2005,cd8,07/11/2005,14.15
3421,07/15/2005,cd9,08/12/2005,15.54


I really appreciate if someone can give solution for this using a query (SQL server,Access,Foxpro) is fine.

I am able to do this oracle using count(trandt) over(partition trandt order by 1) as cnt.

and cnt=1.

If u want I can post that too for getting any idea.

I need more information. I would assume that idno is the primary key on both tables, except that it is not unique for each row. If the key is the idno and the date column on each table, then you will not be able to perform this query as you won't be able to join the two tables together. I will attempt the query, but I am not sure it is what you want without knowing more information. Please reply to let me know whether this answere your question, or whether you need more help. As you either want the current month's cycdt or the next months, I suggest join to two copies of the second table, one joining on the same month, one joining on the subsequent month:

select

case t1.transdt > t2a.cycdt

then t2b.cycdt -- get next month's cycdt

else t2a.cycdt -- get this month's cycdt

end as cycdt,

case t1.transdt > t2a.cycdt

then t2b.amt -- get next month's amt

else t2a.amt -- get next month's amt

end as amt

from table1 as t1

join table2 as t2a -- current month join

on t2a.idno = t1.idno and month(t2a.cycdt) = month(t1.transdt)

join table2 as t2b -- joins to next month.

on t2b.idno = t1.idno and month(t2b.cycdt) = month(t1.transdt) + 1

-- The second join may need to be an outer join, as will restrict result set to

-- include only dates upto the month before the latest month. I don't know if

-- this is going to be a problem for you

For more T-SQL tips and advice, visit my blog:

|||

Whoops, forgot the first three columns.

select

t1.Idno,

t1.transdt,

t1.cd,

case

when t1.transdt > t2a.cycdt then t2b.cycdt -- get next month's cycdt

else t2a.cycdt -- get this month's cycdt

end as cycdt,

case when t1.transdt > t2a.cycdt then t2b.amt -- get next month's amt

else t2a.amt -- get next month's amt

end as amt

from table1 as t1

join table2 as t2a -- current month join

on t2a.idno = t1.idno and month(t2a.cycdt) = month(t1.transdt)

join table2 as t2b -- joins to next month.

on t2b.idno = t1.idno and month(t2b.cycdt) = month(t1.transdt) + 1

|||

First, I really appreciate you in taking time to write the query.

Basically, its not a formal table but just set of two result set and need to produce report out of it as one time. so, I am not making it as any primary key or something. But Idno is the main link between the tables.

Also, this is test tables as my original tables have 3million in table1 and 500k in table2.

The solution you had given works fine as long as there are no missing cycdt in between. But if one cycdt misses the query is not pulling the proper records.

(E.g) try removing the record 12345,05/24/05 from table2.

Let me know if you need more info.

I have this in Oracle but not able to use "Over - Partition" thing since I am using SQL server 8.0

Here it is in Oracle.


SELECT IDNO,TRANDT,IDNO1,CYCDT,AMT FROM
(SELECT IDNO,TRANDT,IDNO1,CYCDT,AMT,COUNT(TRANDT) OVER(PARTITION BY TRANDT ORDER BY 1) CNT
FROM
( SELECT T1.IDNO IDNO,T1.TRANDT,T2.IDNO IDNO1,T2.CYCDT,T2.AMT
FROM tab1 T1,tab2 T2 WHERE T1.IDNO=T2.IDNO )
WHERE (TO_CHAR(TRANDT,'MM') = TO_CHAR(CYCDT,'MM') AND
TO_CHAR(TRANDT,'DD') < TO_CHAR(CYCDT,'DD')) OR
(TO_NUMBER(TO_CHAR(TRANDT,'MM'))+1 = TO_CHAR(CYCDT,'MM'))
ORDER BY 1,2,4
)
WHERE TO_CHAR(TRANDT,'MM') = TO_CHAR(CYCDT,'MM') OR CNT=1ORDER BY 1 DESC,2,4

|||Use LEFT OUTER JOINS on both the JOINS instead, in which case when cycdt is null, then the columns from the second table will be null. You can then test for this using ISNULL, and specify the value to return in this case.

Friday, February 24, 2012

Complex counting, joining and grouping

I have a sales stats table and I want to do some counting and grouping by
source and cluster (join required).
The 2 tables and sample data are as follows:
CREATE TABLE
dbo.stat (id_source varchar(10) not null,
id_period int not null,
id_dept varchar(10) not null,
ind_Domestic char(1) not null,
trade_count int not null)
CREATE TABLE dbo.stat_Hierarchy(id_dept varchar(5) not null,
id_cluster varchar(10) not null)
INSERT INTO stat VALUES('INTERNET',200601,'N41','Y',250)
INSERT INTO stat VALUES('INTERNET',200601,'N41','N',100)
INSERT INTO stat VALUES('INTERNET',200601,'S51','Y',200)
INSERT INTO stat VALUES('INTERNET',200601,'S51','N',120)
INSERT INTO stat VALUES('INTERNET',200601,'021','Y',50)
INSERT INTO stat VALUES('INTERNET',200601,'021','N',70)
INSERT INTO stat VALUES('INTERNET',200601,'131','Y',30)
INSERT INTO stat VALUES('INTERNET',200601,'131','N',70)
INSERT INTO stat VALUES('STORE',200601,'00P','Y',130)
INSERT INTO stat VALUES('STORE',200601,'00P','N',1)
INSERT INTO stat VALUES('STORE',200601,'00S','N',100)
INSERT INTO stat VALUES('STORE',200601,'N41','Y',130)
INSERT INTO stat VALUES('STORE',200601,'N41','N',250)
INSERT INTO stat VALUES('STORE',200601,'S51','Y',110)
INSERT INTO stat VALUES('STORE',200601,'S51','N',320)
INSERT INTO stat VALUES('STORE',200601,'021','Y',30)
INSERT INTO stat VALUES('STORE',200601,'021','N',40)
INSERT INTO stat VALUES('AGENCY',200601,'0101','Y',50)
INSERT INTO stat VALUES('AGENCY',200601,'0101','N',10)
INSERT INTO stat VALUES('AGENCY',200601,'0100300','Y',100
)
INSERT INTO stat VALUES('AGENCY',200601,'0100300','N',320
)
INSERT INTO stat VALUES('AGENCY',200601,'021','Y',150)
INSERT INTO stat VALUES('AGENCY',200601,'021','N',50)
INSERT INTO stat VALUES('AGENCY',200601,'131','Y',20)
INSERT INTO stat VALUES('AGENCY',200601,'131','N',80)
INSERT INTO stat_Hierarchy VALUES('00P','IB_CL_OTHE')
INSERT INTO stat_Hierarchy VALUES('00S','IB_CL_OTHE')
INSERT INTO stat_Hierarchy VALUES('0101','LV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('021','LV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('131','LV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('0100300','HV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('N41','HV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('S51','HV_CL_SALE')
And I want the data to be returned like so:
id_cluster,id_source,ind_Domestic,trade_
count
HV_CL_SALE,INTERNET,N,220
HV_CL_SALE,INTERNET,Y,450
HV_CL_SALE,STORE,N,570
HV_CL_SALE,STORE,Y,240
IB_CL_OTHE,STORE,N,101
IB_CL_OTHE,STORE,Y,130
LV_CL_SALE,AGENCY,N,140
LV_CL_SALE,AGENCY,Y,200
LV_CL_SALE,INTERNET,N,140
LV_CL_SALE,INTERNET,Y,80
LV_CL_SALE,STORE,N,40
LV_CL_SALE,STORE,Y,30
How could I do this?select
h.id_cluster,
s.id_source,
s.ind_Domestic,
sum(s.trade_count) as trade_count
from stat s
inner join stat_Hierarchy h on h.id_dept=s.id_dept
group by h.id_cluster,s.id_source,s.ind_Domestic
order by h.id_cluster,s.id_source,s.ind_Domestic

Complex counting, joining and grouping

I have a sales stats table and I want to do some counting and grouping by
source and cluster (join required).
The 2 tables and sample data are as follows:
CREATE TABLE
dbo.stat (id_source varchar(10) not null,
id_period int not null,
id_dept varchar(10) not null,
ind_Domestic char(1) not null,
trade_count int not null)
CREATE TABLE dbo.stat_Hierarchy(id_dept varchar(5) not null,
id_cluster varchar(10) not null)
INSERT INTO stat VALUES('INTERNET',200601,'N41','Y',250)
INSERT INTO stat VALUES('INTERNET',200601,'N41','N',100)
INSERT INTO stat VALUES('INTERNET',200601,'S51','Y',200)
INSERT INTO stat VALUES('INTERNET',200601,'S51','N',120)
INSERT INTO stat VALUES('INTERNET',200601,'021','Y',50)
INSERT INTO stat VALUES('INTERNET',200601,'021','N',70)
INSERT INTO stat VALUES('INTERNET',200601,'131','Y',30)
INSERT INTO stat VALUES('INTERNET',200601,'131','N',70)
INSERT INTO stat VALUES('STORE',200601,'00P','Y',130)
INSERT INTO stat VALUES('STORE',200601,'00P','N',1)
INSERT INTO stat VALUES('STORE',200601,'00S','N',100)
INSERT INTO stat VALUES('STORE',200601,'N41','Y',130)
INSERT INTO stat VALUES('STORE',200601,'N41','N',250)
INSERT INTO stat VALUES('STORE',200601,'S51','Y',110)
INSERT INTO stat VALUES('STORE',200601,'S51','N',320)
INSERT INTO stat VALUES('STORE',200601,'021','Y',30)
INSERT INTO stat VALUES('STORE',200601,'021','N',40)
INSERT INTO stat VALUES('AGENCY',200601,'0101','Y',50)
INSERT INTO stat VALUES('AGENCY',200601,'0101','N',10)
INSERT INTO stat VALUES('AGENCY',200601,'0100300','Y',100)
INSERT INTO stat VALUES('AGENCY',200601,'0100300','N',320)
INSERT INTO stat VALUES('AGENCY',200601,'021','Y',150)
INSERT INTO stat VALUES('AGENCY',200601,'021','N',50)
INSERT INTO stat VALUES('AGENCY',200601,'131','Y',20)
INSERT INTO stat VALUES('AGENCY',200601,'131','N',80)
INSERT INTO stat_Hierarchy VALUES('00P','IB_CL_OTHE')
INSERT INTO stat_Hierarchy VALUES('00S','IB_CL_OTHE')
INSERT INTO stat_Hierarchy VALUES('0101','LV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('021','LV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('131','LV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('0100300','HV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('N41','HV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('S51','HV_CL_SALE')
And I want the data to be returned like so:
id_cluster,id_source,ind_Domestic,trade_count
HV_CL_SALE,INTERNET,N,220
HV_CL_SALE,INTERNET,Y,450
HV_CL_SALE,STORE,N,570
HV_CL_SALE,STORE,Y,240
IB_CL_OTHE,STORE,N,101
IB_CL_OTHE,STORE,Y,130
LV_CL_SALE,AGENCY,N,140
LV_CL_SALE,AGENCY,Y,200
LV_CL_SALE,INTERNET,N,140
LV_CL_SALE,INTERNET,Y,80
LV_CL_SALE,STORE,N,40
LV_CL_SALE,STORE,Y,30
How could I do this?
select
h.id_cluster,
s.id_source,
s.ind_Domestic,
sum(s.trade_count) as trade_count
from stat s
inner join stat_Hierarchy h on h.id_dept=s.id_dept
group by h.id_cluster,s.id_source,s.ind_Domestic
order by h.id_cluster,s.id_source,s.ind_Domestic

Complex counting, joining and grouping

I have a sales stats table and I want to do some counting and grouping by
source and cluster (join required).
The 2 tables and sample data are as follows:
CREATE TABLE
dbo.stat (id_source varchar(10) not null,
id_period int not null,
id_dept varchar(10) not null,
ind_Domestic char(1) not null,
trade_count int not null)
CREATE TABLE dbo.stat_Hierarchy(id_dept varchar(5) not null,
id_cluster varchar(10) not null)
INSERT INTO stat VALUES('INTERNET',200601,'N41','Y',250)
INSERT INTO stat VALUES('INTERNET',200601,'N41','N',100)
INSERT INTO stat VALUES('INTERNET',200601,'S51','Y',200)
INSERT INTO stat VALUES('INTERNET',200601,'S51','N',120)
INSERT INTO stat VALUES('INTERNET',200601,'021','Y',50)
INSERT INTO stat VALUES('INTERNET',200601,'021','N',70)
INSERT INTO stat VALUES('INTERNET',200601,'131','Y',30)
INSERT INTO stat VALUES('INTERNET',200601,'131','N',70)
INSERT INTO stat VALUES('STORE',200601,'00P','Y',130)
INSERT INTO stat VALUES('STORE',200601,'00P','N',1)
INSERT INTO stat VALUES('STORE',200601,'00S','N',100)
INSERT INTO stat VALUES('STORE',200601,'N41','Y',130)
INSERT INTO stat VALUES('STORE',200601,'N41','N',250)
INSERT INTO stat VALUES('STORE',200601,'S51','Y',110)
INSERT INTO stat VALUES('STORE',200601,'S51','N',320)
INSERT INTO stat VALUES('STORE',200601,'021','Y',30)
INSERT INTO stat VALUES('STORE',200601,'021','N',40)
INSERT INTO stat VALUES('AGENCY',200601,'0101','Y',50)
INSERT INTO stat VALUES('AGENCY',200601,'0101','N',10)
INSERT INTO stat VALUES('AGENCY',200601,'0100300','Y',100)
INSERT INTO stat VALUES('AGENCY',200601,'0100300','N',320)
INSERT INTO stat VALUES('AGENCY',200601,'021','Y',150)
INSERT INTO stat VALUES('AGENCY',200601,'021','N',50)
INSERT INTO stat VALUES('AGENCY',200601,'131','Y',20)
INSERT INTO stat VALUES('AGENCY',200601,'131','N',80)
INSERT INTO stat_Hierarchy VALUES('00P','IB_CL_OTHE')
INSERT INTO stat_Hierarchy VALUES('00S','IB_CL_OTHE')
INSERT INTO stat_Hierarchy VALUES('0101','LV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('021','LV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('131','LV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('0100300','HV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('N41','HV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('S51','HV_CL_SALE')
And I want the data to be returned like so:
id_cluster,id_source,ind_Domestic,trade_count
HV_CL_SALE,INTERNET,N,220
HV_CL_SALE,INTERNET,Y,450
HV_CL_SALE,STORE,N,570
HV_CL_SALE,STORE,Y,240
IB_CL_OTHE,STORE,N,101
IB_CL_OTHE,STORE,Y,130
LV_CL_SALE,AGENCY,N,140
LV_CL_SALE,AGENCY,Y,200
LV_CL_SALE,INTERNET,N,140
LV_CL_SALE,INTERNET,Y,80
LV_CL_SALE,STORE,N,40
LV_CL_SALE,STORE,Y,30
How could I do this?select
h.id_cluster,
s.id_source,
s.ind_Domestic,
sum(s.trade_count) as trade_count
from stat s
inner join stat_Hierarchy h on h.id_dept=s.id_dept
group by h.id_cluster,s.id_source,s.ind_Domestic
order by h.id_cluster,s.id_source,s.ind_Domestic