Showing posts with label following. Show all posts
Showing posts with label following. Show all posts

Friday, March 30, 2012

Jump to URL Error

I'm trying to put a hyperlink in a field on a report. I've found the action property and set the "Jump To" box with the following:

="http://dveowb01.wbhq.com/UnitsStatusLog/StatusEntry.aspx?Unit=" & Fields!Unit.Value

I'm getting this error message:

The Hyperlink expression for the textbox ‘textbox24’ refers to the field ‘Unit’. Report item expressions can only refer to fields within the current data set scope or, if inside an aggregate, the specified data set scope.

Please help.

Thanks,

Jennifer

1. Click View -> Datasets from within your report server project.
2. Expand the dataset that is associated with the table or matrix in your report that this field references.

3. If the Unit field is not in the list for that dataset, right click the dataset and then click refresh. The field should now appear in the list.

4. Rebuild and deploy the report.

|||

If the text box that you have set the property on is not in a data region (list, table, or matrix) you will need to use an aggregator to access values from a dataset. Either add the text box to a list and let the list provide you with one copy of the text box for each item in the data set or change your formula to:

Code Snippet

="http://dveowb01.wbhq.com/UnitsStatusLog/StatusEntry.aspx?Unit="&First(Fields!Unit.Value)

and the first value will be used. A real easy way to get the expression, including scoping string, is to drag the field onto your report from the Datasets tab to your report. This will create a text box with an aggregator expression (first or sum) as the value.

To create a list and bind it to your data set, add the list and then on the properties tab (hit F4 if you don't see it) set the DataSetName property to be the data set with the field 'Unit'. Add your current text box to the list by dragging it over the list and dropping it once the pointer changes to the arrow with the attached small box.

Good luck!

Larry

Jump to URL

Hi,

I want to navigate to a webpage from my report. On clicking a report field that web page should be opened. I have written the following code,

Function OpenWindow (ByVal DealerId as Integer,ByVal CustomerNo as string,ByVal InvoiceNo as string, ByVal CustomerType as string,ByVal CustomerStatus as string,ByVal AppilcationName as string,ByVal UserId as string,ByVal CallStatus as string)as String

Dim strURL as String
Dim strTargetURL as String
Dim strFeatures as String

If CustomerType = "EXTERNAL" and CustomerStatus <> "Completed"
strURL = AppilcationName & "?" & "DealerId="& DealerId &"&CustomerNo="&CustomerNo &"&InvoiceNo="&InvoiceNo & "&UserId=" & UserId & "&CallStatus=" &CallStatus

strTargetURL = "javascript:void(window.open('"
strTargetURL = strTargetURL & strURL & "'"
strTargetURL = strTargetURL & ",'',"

strFeatures = "' width=1000,height=720,scrollbars=yes, status=no, toolbar=no, resizable=no, left=0, top=0'"

strTargetURL = strTargetURL & strFeatures
strTargetURL = strTargetURL & ",'_blank'));"

End If
Return strTargetURL

End Function

Now If I click the report field my web page is opening in a new page. But if I select the option "Open in New Window" an empty page as well as my web page is being opened. How to avoid the opening of empty page.

Help of any kind to this problem is welcome

Thanks in Advance,

Sivaatzenith

It seems that you should maybe just assign the href of the url, and not use the javascript. Personally, I don't like it when a site wants to size and/or position a window with/without various options... I guess I kookie like that :)

|||

Hi Ben,

Thanks for your reply

Can you pls give a sample containing the href in jump to url code

Regards

Sivaatzenith

|||

Sivaatzenith,

My thought was that in your OpenWindow code, you omit the javascript code...

So perhaps:
strTargetURL = "javascript:void(window.open('"
strTargetURL = strTargetURL & strURL & "'"
strTargetURL = strTargetURL & ",'',"

strFeatures = "' width=1000,height=720,scrollbars=yes, status=no, toolbar=no, resizable=no, left=0, top=0'"

strTargetURL = strTargetURL & strFeatures
strTargetURL = strTargetURL & ",'_blank'));"

becomes:
strTargetURL = strURL

I am not really sure if this will work in Sql Reporting Services or not...

Good Luck

|||

hi,

Thanks for ur reply... First I had given the following code in jump to URL

STRURL ="http:mail.yahoo.com"

Mine is a web application. The reports will be launched by web application which is in .net.These reports will be shown in report viewer ctrl. This report will also contain subreport, which will be displayed on clicking of a textbox. When I click this textbox to view the sub report and after that press the link (jump to url) I am getting a java script error... Actually thats a problem with report viewer after googling I found out that microsoft has provided a hot fix for this which is extra money. So I tried this.

Any other solution is welcome.. I tired using <a href also. but of no use... I am getting a run time error.

Thanks in advance

Sivaatzenith

|||

I apologize that I am not more familiar with reporting services, what is your specific javascript error?

|||

hi Ben,

If I click the link, my desired web page is opened in a new browser. But If I select the option "Open in a new page" an empty browser as well as my page is opened. I need to avoid this empty page.

Thanks in Advance,

Sivaatzenith.

Jump to URL

to open a report in a new window

i looked up the following line of code

=window.open('" & Globals!ReportServerUrl & "?" & Globals!ReportFolder & "/" & "myreport" & "&amp;rs:Command=Render&amp;rc:toolbar=true','','width=800,height=600,left=10,top=10,resizable=1,menubar=no,location=no,status=no'),_top"

I do not understand what & Globals!ReportServerUrl & "?" & Globals!ReportFolder & "/" & "myreport" &

this implies.

I have the current report name as

http://houapps277/ReportServer/Pages/ReportViewer.aspx?%2fIMS-Reports%2fCR000648

and I need to jump to

http://houapps277/ReportServer/Pages/ReportViewer.aspx?%2fIMS-Reports%2fCR000699

both reports are in same folder IMS-Reports.

Thanks

"javascript:void window.open('ReportViewer.aspx? %2fCR000699', '_top', 'location=0, menubar=0, toolbar=0, resizable=1, width=800')"


use the above code.

In reportviewer.aspx page you need to write the code as

rptViewer.ServerReport.ReportServerUrl = new Uri(http://Reportservername);

rptViewer.ServerReport.ReportPath = "/IMS-Reports/" + Request.QueryString[0];

rptViewer.ProcessingMode = ProcessingMode.Remote;

Hope it will help you

Rakam.

|||

Thanks for the reply rakam,

Where do I write and store reportviewer.aspx?

Sorry for being illiterate here.

Thanks

|||

Just use the following code

"javascript:void window.open('http://houapps277/ReportServer/Pages/ReportViewer.aspx?%2fIMS-Reports%2fCR000699', '_top', 'location=0, menubar=0, toolbar=0, resizable=1, width=800')"

hope it will work

sql

Monday, March 26, 2012

Julian Dates

I want to derive a date from a string field where the string will have the date embeded in the following format YYJJJ, for example 02364 = Dec 30 2002. Is there a way to do this using Transact-Sql via Sql Server?-- If it where in a procedure
DECLARE @.strDate varchar(5)
DECLARE @.dtDate smalldatetime

SET @.strDate = '02364'

SET @.dtDate = DATEADD(dd, CAST(RIGHT(@.strDate, 3) AS integer) - 1, CONVERT(smalldatetime,'01/01/' + LEFT(@.strDate, 2), 3))

SELECT @.dtDate

-- Using within a query
CREATE TABLE #tmp_mydates (mydate varchar(5))

INSERT INTO #tmp_mydates VALUES ('02364')
INSERT INTO #tmp_mydates VALUES ('02264')
INSERT INTO #tmp_mydates VALUES ('02164')
INSERT INTO #tmp_mydates VALUES ('02004')
INSERT INTO #tmp_mydates VALUES ('02002')

SELECT mydate, DATEADD(dd, CAST(RIGHT(mydate, 3) AS integer) - 1, CONVERT(smalldatetime,'01/01/' + LEFT(mydate, 2), 3)) AS myconverteddate FROM #tmp_mydates|||I want to derive a date from a string field where the string will have the date embeded in the following format YYJJJ, for example 02364 = Dec 30 2002. Is there a way to do this using Transact-Sql via Sql Server?

Q1 [Is there a way to do this using Transact-Sql via Sql Server?]
A1 You may consider creating your own derived "JulianDate" user datatype; and also creating your own user functions or stored procedures to properly interpet, convert to and from, and generally handle them as you might require. (I've found the strategy helpful in handling similar customized Julian date formats for special applications) For example:
dbo.fn_MyJulianDate_Add,
dbo.fn_MyJulianDate_Diff,
dbo.fn_ConvertStandardDate_To_MyJulianDate, dbo.fn_ConvertMyJulianDate_To_StandardDate,
etc.

JULIAN DATE

No Doubt Julian Date conversion is a PAIN in RS. After reading many postings
I came up with the following on the fly conversion for a julian date in our
AS/400 system:
In order to convert the following date 107306 to the regular date: 11/3/2007
I used the following:
First of, the first 2 digits denote the Century: 00 stands for 1900 and 10
stands for 2000
So in the case of 107306 the first 3 digits stand for 2007 and the last 3
stand for number of days.
Here's the formula:
=DATEADD("d", Val(Right(Fields!TransactionDate.Value,3)), "#01/01/200" & Cstr
(Mid(Fields!TransactionDate.Value,3,1)) & "#")
I just wish that when Microsoft marketed RS they had their act together as
far as usability is cocerned, you almost have to be a rocket scientist to
make the reports half way decent! and DON'T get me started on the
ridiculously limited charting functionality!!! Being a recovering Crystal-
holic it has been an absolute BEAR to mimic functionality and looks...
--
Message posted via SQLMonster.com
http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server-reporting/200712/1On Dec 12, 12:14 pm, "patrickpk via SQLMonster.com" <u38565@.uwe>
wrote:
> No Doubt Julian Date conversion is a PAIN in RS. After reading many postings
> I came up with the following on the fly conversion for a julian date in our
> AS/400 system:
> In order to convert the following date 107306 to the regular date: 11/3/2007
> I used the following:
> First of, the first 2 digits denote the Century: 00 stands for 1900 and 10
> stands for 2000
> So in the case of 107306 the first 3 digits stand for 2007 and the last 3
> stand for number of days.
> Here's the formula:
> =DATEADD("d", Val(Right(Fields!TransactionDate.Value,3)), "#01/01/200" & Cstr
> (Mid(Fields!TransactionDate.Value,3,1)) & "#")
> I just wish that when Microsoft marketed RS they had their act together as
> far as usability is cocerned, you almost have to be a rocket scientist to
> make the reports half way decent! and DON'T get me started on the
> ridiculously limited charting functionality!!! Being a recovering Crystal-
> holic it has been an absolute BEAR to mimic functionality and looks...
> --
> Message posted via SQLMonster.comhttp://www.sqlmonster.com/Uwe/Forums.aspx/sql-server-reporting/200712/1
I don't know what your date format is, but it isn't a Julian Date --
it's some kind of weird mainframe hybrid of Century, Year and
DayOfYear. A Julian Date is a count of days since Jan 1st, 4713 BC.
(See http://aa.usno.navy.mil/data/docs/JulianDate.php). The Julian
date for 11/3/2007 is 2,454,408.
For you, the following .Net formula works to convert to 11/3/2007, and
it gets your 1900-2000 span right too (replace the number with your
Fields...Value):
= #1/1/1900#.AddYears( Floor( 107306 / 1000) ).AddDays( 107306 Mod
1000 )
If you needed to go backwards for some reason, this works (replace the
date with your Fields...Value) :
= 1000 * ( CDate(#11/3/2007#).Year - 1900 ) +
CDate(#11/3/2007#).DayOfYear - 1
-- Scottsql

Joins with XQuery

Hello,
I have a very simple data table:

CREATE TABLE [ALMPayloads]([ID] [int] NOT NULL,[OutputPayload] [xml] NOT NULL)

with the following content:

ID = 1
OutputPayload:

<ReportDocument>
<ALMSimulationResult>
<selectedModelAssets>
<modelAsset ID="8bc798ae-cc15-4807-8805-61ecfc8f3c01" description="Global Bond" internationalCode=" " minimumLimit="0" maximumLimit="1" annualManagementFee="0" annualPerformanceFee="0" initialCostUpFront="0.02" regularCostUpFront="0.015" withdrawingCommission="0" switchCostPercentage="0" switchCostAmount="0" color="#FF00FFD4" stochasticDuration="5">
<models>
<model ID="0e70216f-48ce-4f6c-b2d6-519a5cdfd246" type="corporate grade bond" description="Eurozone Corporate Bond Intermediate (D=5Years)" weight="1" />
</models>
</modelAsset>
<modelAsset ID="eab258b2-57ba-4d67-9f36-ee4e17c10dec" description="America Value Fund" internationalCode=" " minimumLimit="0" maximumLimit="1" annualManagementFee="0" annualPerformanceFee="0.005" initialCostUpFront="0.03" regularCostUpFront="0.03" withdrawingCommission="0" switchCostPercentage="0" switchCostAmount="0" color="#FF3B00FF" stochasticDuration="13.55">
<models>
<model ID="b0817f64-5090-48a3-b58c-aa8f6e5bbdc1" type="equity" description="US Value Style (Eur)" weight="0.9" />
<model ID="677e8aae-7b32-4dc3-88c5-e9302dddad8f" type="conventional bond" description="Euro Cash (TBill)" weight="0.1" />
</models>
</modelAsset>
<modelAsset ID="0e2e95bb-bec0-4dcb-bb13-2032f3ed0978" description="Europa Value Fund" internationalCode=" " minimumLimit="0" maximumLimit="1" annualManagementFee="0.001" annualPerformanceFee="0.001" initialCostUpFront="0.03" regularCostUpFront="0.03" withdrawingCommission="0" switchCostPercentage="0" switchCostAmount="0" color="#FF9D00FF" stochasticDuration="17.5">
<models>
<model ID="86fedd24-2a92-422c-b733-17c60105ff81" type="equity" description="Asia Value Style (Eur)" weight="0.1" />
<model ID="55425529-8adc-47d8-a36d-8cfd9da34880" type="conventional bond" description="Italian Long Term Gov Bond" weight="0.1" />
<model ID="fea29db9-cf0e-4802-bcbe-e2b8d367f0ca" type="cash" description="Euro Cash (Euribor 1m)" weight="0.1" />
<model ID="8e58d785-5fc5-4ede-8ec8-eb1af8e62541" type="equity" description="Eurozone Value Style" weight="0.7" />
</models>
</modelAsset>
</selectedModelAssets>
<savingModelAsset ID="0e2e95bb-bec0-4dcb-bb13-2032f3ed0978" />
<surplusModelAsset ID="0e2e95bb-bec0-4dcb-bb13-2032f3ed0978" />
<modelAssetTimeSeries>
<modelAsset ID="8bc798ae-cc15-4807-8805-61ecfc8f3c01">
<tValues t="0" value="0" annualYield="0" />
<tValues t="1" value="0" annualYield="0.027353" />
<tValues t="2" value="0" annualYield="0.027288" />
<tValues t="3" value="0" annualYield="0.027237" />
<tValues t="4" value="0" annualYield="0.027274" />
<tValues t="5" value="0" annualYield="0.027262" />
<tValues t="6" value="0" annualYield="0.02722" />
<tValues t="7" value="1453" annualYield="0.027258" />
<tValues t="8" value="1457" annualYield="0.027258" />
<tValues t="9" value="1460" annualYield="0.027219" />
<tValues t="10" value="1463" annualYield="0.027259" />
</modelAsset>
<modelAsset ID="eab258b2-57ba-4d67-9f36-ee4e17c10dec">
<tValues t="0" value="0" annualYield="0" />
<tValues t="1" value="0" annualYield="0.065466" />
<tValues t="2" value="0" annualYield="0.063841" />
<tValues t="3" value="0" annualYield="0.063707" />
<tValues t="4" value="0" annualYield="0.063692" />
<tValues t="5" value="0" annualYield="0.062438" />
<tValues t="6" value="0" annualYield="0.064081" />
<tValues t="7" value="0" annualYield="0.063476" />
<tValues t="8" value="0" annualYield="0.064294" />
<tValues t="9" value="0" annualYield="0.062034" />
<tValues t="10" value="0" annualYield="0.065144" />
</modelAsset>
<modelAsset ID="0e2e95bb-bec0-4dcb-bb13-2032f3ed0978">
<tValues t="0" value="830" annualYield="0" />
<tValues t="1" value="1641" annualYield="0.06504" />
<tValues t="2" value="2456" annualYield="0.063229" />
<tValues t="3" value="3278" annualYield="0.062939" />
<tValues t="4" value="4104" annualYield="0.062825" />
<tValues t="5" value="4935" annualYield="0.061233" />
<tValues t="6" value="5772" annualYield="0.063522" />
<tValues t="7" value="5155" annualYield="0.062448" />
<tValues t="8" value="5994" annualYield="0.063548" />
<tValues t="9" value="6837" annualYield="0.061053" />
<tValues t="10" value="7688" annualYield="0.06525" />
</modelAsset>
</modelAssetTimeSeries>
</ALMSimulationResult>
</ReportDocument>

When I run the following command from SQL server:

SELECT
N.ma.value('@.ID', 'uniqueidentifier') as ModelAssetID,
N.ma.value('@.description', 'nvarchar(255)') as ModelAssetDescription,
N.ma.value('@.minimumLimit', 'float') as ModelAssetMinLimit,
N.ma.value('@.maximumLimit', 'float') as ModelAssetMaxLimit,
N.ma.value('@.stochasticDuration', 'float') as ModelAssetDuration,
N.ma.value('@.color', 'char(9)') as Color,
N1.ma1.value('tValues[1]/@.value', 'float') as ActualAssetMix
FROM ALMPayloads A1 CROSS APPLY OutputPayload.nodes('/ReportDocument/ALMSimulationResult/selectedModelAssets/modelAsset') N(ma)
LEFT JOIN ALMPayloads A2 CROSS APPLY OutputPayload.nodes('/ReportDocument/ALMSimulationResult/modelAssetTimeSeries/modelAsset') N1(ma1)
ON N.ma.value('@.ID', 'uniqueidentifier') = N1.ma1.value('@.ID', 'uniqueidentifier')
WHERE A1.ID = 1000
ORDER BY ModelAssetDuration

I get the following result:

ModelAssetID ModelAssetDescription Min Max Dur. Color Value
8BC798AE-CC15-4807-8805-61ECFC8F3C01 Global Bond 0 1 5 #FF00FFD4 0
8BC798AE-CC15-4807-8805-61ECFC8F3C01 Global Bond 0 1 5 #FF00FFD4 0
EAB258B2-57BA-4D67-9F36-EE4E17C10DEC America Value Fund 0 1 13.55 #FF3B00FF 0
EAB258B2-57BA-4D67-9F36-EE4E17C10DEC America Value Fund 0 1 13.55 #FF3B00FF 0
0E2E95BB-BEC0-4DCB-BB13-2032F3ED0978 Europa Value Fund 0 1 17.5 #FF9D00FF 96803
0E2E95BB-BEC0-4DCB-BB13-2032F3ED0978 Europa Value Fund 0 1 17.5 #FF9D00FF 830
0E2E95BB-BEC0-4DCB-BB13-2032F3ED0978 Europa Value Fund 0 1 17.5 #FF9D00FF 830

Instead of

ModelAssetID ModelAssetDescription Min Max Dur. Color Value
8BC798AE-CC15-4807-8805-61ECFC8F3C01 Global Bond 0 1 5 #FF00FFD4 0
EAB258B2-57BA-4D67-9F36-EE4E17C10DEC America Value Fund 0 1 13.55 #FF3B00FF 0
0E2E95BB-BEC0-4DCB-BB13-2032F3ED0978 Europa Value Fund 0 1 17.5 #FF9D00FF 830

Why do I have so much duplicates and some random results (I mean the value where I get 96803) ?

Thanks,
Pierre

Pierre, I just tried running the following query. At first, I got no results. When I changed the AI.ID predicate to AI.ID = 1 then I got three rows back (your expected results).

Are you sure there is not other data in the table? I notice that you are doing a self join on the the table [ALMPayloads] but I don't see any predicate on the A2 table alias. I suspect that this could be the reason why you are seeing the additional rows in your results if in fact there are other rows in that table.|||Hi John,
try to add another record (the same xml content with 2 different IDs) and the result will be duplicated.

How can I make the join (on xml data) with the expected result ?

Thanks,
Pierre|||You need to add "AND A1.ID = A2.ID" to your join condition. If you don't need the LEFT JOIN semantics, you can do away with the self join and add another CROSS APPLY.

ALMPayloads A1
CROSS APPLY OutputPayload.nodes('/ReportDocument/ALMSimulationResult/selectedModelAssets/modelAsset') N(ma)CROSS APPLY OutputPayload.nodes('/ReportDocument/ALMSimulationResult/modelAssetTimeSeries/modelAsset') N1(ma1)

sql

Joins with XQuery

Hello,
I have a very simple data table:

CREATE TABLE [ALMPayloads]([ID] [int] NOT NULL,[OutputPayload] [xml] NOT NULL)

with the following content:

ID = 1
OutputPayload:

<ReportDocument>
<ALMSimulationResult>
<selectedModelAssets>
<modelAsset ID="8bc798ae-cc15-4807-8805-61ecfc8f3c01" description="Global Bond" internationalCode=" " minimumLimit="0" maximumLimit="1" annualManagementFee="0" annualPerformanceFee="0" initialCostUpFront="0.02" regularCostUpFront="0.015" withdrawingCommission="0" switchCostPercentage="0" switchCostAmount="0" color="#FF00FFD4" stochasticDuration="5">
<models>
<model ID="0e70216f-48ce-4f6c-b2d6-519a5cdfd246" type="corporate grade bond" description="Eurozone Corporate Bond Intermediate (D=5Years)" weight="1" />
</models>
</modelAsset>
<modelAsset ID="eab258b2-57ba-4d67-9f36-ee4e17c10dec" description="America Value Fund" internationalCode=" " minimumLimit="0" maximumLimit="1" annualManagementFee="0" annualPerformanceFee="0.005" initialCostUpFront="0.03" regularCostUpFront="0.03" withdrawingCommission="0" switchCostPercentage="0" switchCostAmount="0" color="#FF3B00FF" stochasticDuration="13.55">
<models>
<model ID="b0817f64-5090-48a3-b58c-aa8f6e5bbdc1" type="equity" description="US Value Style (Eur)" weight="0.9" />
<model ID="677e8aae-7b32-4dc3-88c5-e9302dddad8f" type="conventional bond" description="Euro Cash (TBill)" weight="0.1" />
</models>
</modelAsset>
<modelAsset ID="0e2e95bb-bec0-4dcb-bb13-2032f3ed0978" description="Europa Value Fund" internationalCode=" " minimumLimit="0" maximumLimit="1" annualManagementFee="0.001" annualPerformanceFee="0.001" initialCostUpFront="0.03" regularCostUpFront="0.03" withdrawingCommission="0" switchCostPercentage="0" switchCostAmount="0" color="#FF9D00FF" stochasticDuration="17.5">
<models>
<model ID="86fedd24-2a92-422c-b733-17c60105ff81" type="equity" description="Asia Value Style (Eur)" weight="0.1" />
<model ID="55425529-8adc-47d8-a36d-8cfd9da34880" type="conventional bond" description="Italian Long Term Gov Bond" weight="0.1" />
<model ID="fea29db9-cf0e-4802-bcbe-e2b8d367f0ca" type="cash" description="Euro Cash (Euribor 1m)" weight="0.1" />
<model ID="8e58d785-5fc5-4ede-8ec8-eb1af8e62541" type="equity" description="Eurozone Value Style" weight="0.7" />
</models>
</modelAsset>
</selectedModelAssets>
<savingModelAsset ID="0e2e95bb-bec0-4dcb-bb13-2032f3ed0978" />
<surplusModelAsset ID="0e2e95bb-bec0-4dcb-bb13-2032f3ed0978" />
<modelAssetTimeSeries>
<modelAsset ID="8bc798ae-cc15-4807-8805-61ecfc8f3c01">
<tValues t="0" value="0" annualYield="0" />
<tValues t="1" value="0" annualYield="0.027353" />
<tValues t="2" value="0" annualYield="0.027288" />
<tValues t="3" value="0" annualYield="0.027237" />
<tValues t="4" value="0" annualYield="0.027274" />
<tValues t="5" value="0" annualYield="0.027262" />
<tValues t="6" value="0" annualYield="0.02722" />
<tValues t="7" value="1453" annualYield="0.027258" />
<tValues t="8" value="1457" annualYield="0.027258" />
<tValues t="9" value="1460" annualYield="0.027219" />
<tValues t="10" value="1463" annualYield="0.027259" />
</modelAsset>
<modelAsset ID="eab258b2-57ba-4d67-9f36-ee4e17c10dec">
<tValues t="0" value="0" annualYield="0" />
<tValues t="1" value="0" annualYield="0.065466" />
<tValues t="2" value="0" annualYield="0.063841" />
<tValues t="3" value="0" annualYield="0.063707" />
<tValues t="4" value="0" annualYield="0.063692" />
<tValues t="5" value="0" annualYield="0.062438" />
<tValues t="6" value="0" annualYield="0.064081" />
<tValues t="7" value="0" annualYield="0.063476" />
<tValues t="8" value="0" annualYield="0.064294" />
<tValues t="9" value="0" annualYield="0.062034" />
<tValues t="10" value="0" annualYield="0.065144" />
</modelAsset>
<modelAsset ID="0e2e95bb-bec0-4dcb-bb13-2032f3ed0978">
<tValues t="0" value="830" annualYield="0" />
<tValues t="1" value="1641" annualYield="0.06504" />
<tValues t="2" value="2456" annualYield="0.063229" />
<tValues t="3" value="3278" annualYield="0.062939" />
<tValues t="4" value="4104" annualYield="0.062825" />
<tValues t="5" value="4935" annualYield="0.061233" />
<tValues t="6" value="5772" annualYield="0.063522" />
<tValues t="7" value="5155" annualYield="0.062448" />
<tValues t="8" value="5994" annualYield="0.063548" />
<tValues t="9" value="6837" annualYield="0.061053" />
<tValues t="10" value="7688" annualYield="0.06525" />
</modelAsset>
</modelAssetTimeSeries>
</ALMSimulationResult>
</ReportDocument>

When I run the following command from SQL server:

SELECT
N.ma.value('@.ID', 'uniqueidentifier') as ModelAssetID,
N.ma.value('@.description', 'nvarchar(255)') as ModelAssetDescription,
N.ma.value('@.minimumLimit', 'float') as ModelAssetMinLimit,
N.ma.value('@.maximumLimit', 'float') as ModelAssetMaxLimit,
N.ma.value('@.stochasticDuration', 'float') as ModelAssetDuration,
N.ma.value('@.color', 'char(9)') as Color,
N1.ma1.value('tValues[1]/@.value', 'float') as ActualAssetMix
FROM ALMPayloads A1 CROSS APPLY OutputPayload.nodes('/ReportDocument/ALMSimulationResult/selectedModelAssets/modelAsset') N(ma)
LEFT JOIN ALMPayloads A2 CROSS APPLY OutputPayload.nodes('/ReportDocument/ALMSimulationResult/modelAssetTimeSeries/modelAsset') N1(ma1)
ON N.ma.value('@.ID', 'uniqueidentifier') = N1.ma1.value('@.ID', 'uniqueidentifier')
WHERE A1.ID = 1000
ORDER BY ModelAssetDuration

I get the following result:

ModelAssetID ModelAssetDescription Min Max Dur. Color Value
8BC798AE-CC15-4807-8805-61ECFC8F3C01 Global Bond 0 1 5 #FF00FFD4 0
8BC798AE-CC15-4807-8805-61ECFC8F3C01 Global Bond 0 1 5 #FF00FFD4 0
EAB258B2-57BA-4D67-9F36-EE4E17C10DEC America Value Fund 0 1 13.55 #FF3B00FF 0
EAB258B2-57BA-4D67-9F36-EE4E17C10DEC America Value Fund 0 1 13.55 #FF3B00FF 0
0E2E95BB-BEC0-4DCB-BB13-2032F3ED0978 Europa Value Fund 0 1 17.5 #FF9D00FF 96803
0E2E95BB-BEC0-4DCB-BB13-2032F3ED0978 Europa Value Fund 0 1 17.5 #FF9D00FF 830
0E2E95BB-BEC0-4DCB-BB13-2032F3ED0978 Europa Value Fund 0 1 17.5 #FF9D00FF 830

Instead of

ModelAssetID ModelAssetDescription Min Max Dur. Color Value
8BC798AE-CC15-4807-8805-61ECFC8F3C01 Global Bond 0 1 5 #FF00FFD4 0
EAB258B2-57BA-4D67-9F36-EE4E17C10DEC America Value Fund 0 1 13.55 #FF3B00FF 0
0E2E95BB-BEC0-4DCB-BB13-2032F3ED0978 Europa Value Fund 0 1 17.5 #FF9D00FF 830

Why do I have so much duplicates and some random results (I mean the value where I get 96803) ?

Thanks,
Pierre

Pierre, I just tried running the following query. At first, I got no results. When I changed the AI.ID predicate to AI.ID = 1 then I got three rows back (your expected results).

Are you sure there is not other data in the table? I notice that you are doing a self join on the the table [ALMPayloads] but I don't see any predicate on the A2 table alias. I suspect that this could be the reason why you are seeing the additional rows in your results if in fact there are other rows in that table.|||Hi John,
try to add another record (the same xml content with 2 different IDs) and the result will be duplicated.

How can I make the join (on xml data) with the expected result ?

Thanks,
Pierre|||You need to add "AND A1.ID = A2.ID" to your join condition. If you don't need the LEFT JOIN semantics, you can do away with the self join and add another CROSS APPLY.

ALMPayloads A1
CROSS APPLY OutputPayload.nodes('/ReportDocument/ALMSimulationResult/selectedModelAssets/modelAsset') N(ma)CROSS APPLY OutputPayload.nodes('/ReportDocument/ALMSimulationResult/modelAssetTimeSeries/modelAsset') N1(ma1)

Joins Performance Problem

Hello,
It is taking too long to run the following query:
Note: I have indexes on all of the columns in conditions. My temp db size
is 18 GB. Pds_txn table size is 165 GB.
The execution plan showing:
Table pool/easer spool operation â'
Row Count: 9 M
Disk i/o: 11k
Row size: 1089
Estimated cost: 11 k (57%)
CPU cost: 3.3
Sub tree cost: 20 K
Any help/hint will be appreciated.
Thanks,
Alim
-----
FROM
dbo.pds_txn T1
INNER JOIN
dbo.GROUPS T2 ON
T1.GROUP_ID = T2.ID_200
INNER JOIN
dbo.DIVISIONS T3 ON
T1.DIVISION = T3.ID_102
INNER JOIN
dbo.BILLING_AREAS T4 ON
T1.BILLING_AREA = T4.ID_202
INNER JOIN
dbo.PROVIDERS T6 ON
T1.PROVIDER = T6.ID_3
INNER JOIN
dbo.LOCATIONS T7 ON
T1.LOCATION = T7.ID_100
INNER JOIN
dbo.PROCEDURES T8 ON
T1.[PROCEDURE] = T8.ID_1
INNER JOIN
dbo.FSC T9 ON
T1.ORIG_FSC = T9.ID_19
INNER JOIN
dbo.DIAGNOSIS T10 ON
T1.TXN_DX_1 = T10.ID_36
INNER JOIN
dbo.pds_invoice T11 ON
T1.INVOICE_NUM = T11.INVOICE_NUM AND
T1.GROUP_ID = T11.GROUP_ID
LEFT OUTER JOIN
dbo.PROVIDERS T6A ON
T11.PERFORMING_PHYS = T6A.ID_3
WHERE
T1.POSTING_PD_DTE >= '05/01/2003' AND
T1.PAY_CODE = 21 AND
T2.EXCLUSION_FLAG = 0 AND
T3.DIV_NUM <> '2901'Hi Alim,
It is hard to guess what the issue might be without more information. Could
you attach the output of "statistics profile" or "statistics xml" (if you
are using SQL Server 2005) ?
Regards,
Leo
"alim" <alim@.discussions.microsoft.com> wrote in message
news:3873F521-EEF2-4A62-9C66-00C035E1A9CD@.microsoft.com...
> Hello,
> It is taking too long to run the following query:
> Note: I have indexes on all of the columns in conditions. My temp db size
> is 18 GB. Pds_txn table size is 165 GB.
> The execution plan showing:
> Table pool/easer spool operation -
> Row Count: 9 M
> Disk i/o: 11k
> Row size: 1089
> Estimated cost: 11 k (57%)
> CPU cost: 3.3
> Sub tree cost: 20 K
> Any help/hint will be appreciated.
> Thanks,
> Alim
> -----
>
> FROM
> dbo.pds_txn T1
> INNER JOIN
> dbo.GROUPS T2 ON
> T1.GROUP_ID = T2.ID_200
> INNER JOIN
> dbo.DIVISIONS T3 ON
> T1.DIVISION = T3.ID_102
> INNER JOIN
> dbo.BILLING_AREAS T4 ON
> T1.BILLING_AREA = T4.ID_202
> INNER JOIN
> dbo.PROVIDERS T6 ON
> T1.PROVIDER = T6.ID_3
> INNER JOIN
> dbo.LOCATIONS T7 ON
> T1.LOCATION = T7.ID_100
> INNER JOIN
> dbo.PROCEDURES T8 ON
> T1.[PROCEDURE] = T8.ID_1
> INNER JOIN
> dbo.FSC T9 ON
> T1.ORIG_FSC = T9.ID_19
> INNER JOIN
> dbo.DIAGNOSIS T10 ON
> T1.TXN_DX_1 = T10.ID_36
> INNER JOIN
> dbo.pds_invoice T11 ON
> T1.INVOICE_NUM = T11.INVOICE_NUM AND
> T1.GROUP_ID = T11.GROUP_ID
> LEFT OUTER JOIN
> dbo.PROVIDERS T6A ON
> T11.PERFORMING_PHYS = T6A.ID_3
> WHERE
> T1.POSTING_PD_DTE >= '05/01/2003' AND
> T1.PAY_CODE = 21 AND
> T2.EXCLUSION_FLAG = 0 AND
> T3.DIV_NUM <> '2901'
>
>|||Alim,
Need to provide the table/index structure and the query that you are
trying to run..
Jayesh
"Leo Giakoumakis [MS]" <leogia_removethis_@.microsoft.com> wrote in message
news:e8OMTRyiGHA.3848@.TK2MSFTNGP04.phx.gbl...
> Hi Alim,
> It is hard to guess what the issue might be without more information.
> Could you attach the output of "statistics profile" or "statistics xml"
> (if you are using SQL Server 2005) ?
> Regards,
> Leo
>
> "alim" <alim@.discussions.microsoft.com> wrote in message
> news:3873F521-EEF2-4A62-9C66-00C035E1A9CD@.microsoft.com...
>> Hello,
>> It is taking too long to run the following query:
>> Note: I have indexes on all of the columns in conditions. My temp db
>> size
>> is 18 GB. Pds_txn table size is 165 GB.
>> The execution plan showing:
>> Table pool/easer spool operation -
>> Row Count: 9 M
>> Disk i/o: 11k
>> Row size: 1089
>> Estimated cost: 11 k (57%)
>> CPU cost: 3.3
>> Sub tree cost: 20 K
>> Any help/hint will be appreciated.
>> Thanks,
>> Alim
>> -----
>>
>> FROM
>> dbo.pds_txn T1
>> INNER JOIN
>> dbo.GROUPS T2 ON
>> T1.GROUP_ID = T2.ID_200
>> INNER JOIN
>> dbo.DIVISIONS T3 ON
>> T1.DIVISION = T3.ID_102
>> INNER JOIN
>> dbo.BILLING_AREAS T4 ON
>> T1.BILLING_AREA = T4.ID_202
>> INNER JOIN
>> dbo.PROVIDERS T6 ON
>> T1.PROVIDER = T6.ID_3
>> INNER JOIN
>> dbo.LOCATIONS T7 ON
>> T1.LOCATION = T7.ID_100
>> INNER JOIN
>> dbo.PROCEDURES T8 ON
>> T1.[PROCEDURE] = T8.ID_1
>> INNER JOIN
>> dbo.FSC T9 ON
>> T1.ORIG_FSC = T9.ID_19
>> INNER JOIN
>> dbo.DIAGNOSIS T10 ON
>> T1.TXN_DX_1 = T10.ID_36
>> INNER JOIN
>> dbo.pds_invoice T11 ON
>> T1.INVOICE_NUM = T11.INVOICE_NUM AND
>> T1.GROUP_ID = T11.GROUP_ID
>> LEFT OUTER JOIN
>> dbo.PROVIDERS T6A ON
>> T11.PERFORMING_PHYS = T6A.ID_3
>> WHERE
>> T1.POSTING_PD_DTE >= '05/01/2003' AND
>> T1.PAY_CODE = 21 AND
>> T2.EXCLUSION_FLAG = 0 AND
>> T3.DIV_NUM <> '2901'
>>
>

Joins Performance Problem

Hello,
It is taking too long to run the following query:
Note: I have indexes on all of the columns in conditions. My temp db size
is 18 GB. Pds_txn table size is 165 GB.
The execution plan showing:
Table pool/easer spool operation –
Row Count: 9 M
Disk i/o: 11k
Row size: 1089
Estimated cost: 11 k (57%)
CPU cost: 3.3
Sub tree cost: 20 K
Any help/hint will be appreciated.
Thanks,
Alim
----
--
FROM
dbo.pds_txn T1
INNER JOIN
dbo.GROUPS T2 ON
T1.GROUP_ID = T2.ID_200
INNER JOIN
dbo.DIVISIONS T3 ON
T1.DIVISION = T3.ID_102
INNER JOIN
dbo.BILLING_AREAS T4 ON
T1.BILLING_AREA = T4.ID_202
INNER JOIN
dbo.PROVIDERS T6 ON
T1.PROVIDER = T6.ID_3
INNER JOIN
dbo.LOCATIONS T7 ON
T1.LOCATION = T7.ID_100
INNER JOIN
dbo.PROCEDURES T8 ON
T1.[PROCEDURE] = T8.ID_1
INNER JOIN
dbo.FSC T9 ON
T1.ORIG_FSC = T9.ID_19
INNER JOIN
dbo.DIAGNOSIS T10 ON
T1.TXN_DX_1 = T10.ID_36
INNER JOIN
dbo.pds_invoice T11 ON
T1.INVOICE_NUM = T11.INVOICE_NUM AND
T1.GROUP_ID = T11.GROUP_ID
LEFT OUTER JOIN
dbo.PROVIDERS T6A ON
T11.PERFORMING_PHYS = T6A.ID_3
WHERE
T1.POSTING_PD_DTE >= '05/01/2003' AND
T1.PAY_CODE = 21 AND
T2.EXCLUSION_FLAG = 0 AND
T3.DIV_NUM <> '2901'Hi Alim,
It is hard to guess what the issue might be without more information. Could
you attach the output of "statistics profile" or "statistics xml" (if you
are using SQL Server 2005) ?
Regards,
Leo
"alim" <alim@.discussions.microsoft.com> wrote in message
news:3873F521-EEF2-4A62-9C66-00C035E1A9CD@.microsoft.com...
> Hello,
> It is taking too long to run the following query:
> Note: I have indexes on all of the columns in conditions. My temp db size
> is 18 GB. Pds_txn table size is 165 GB.
> The execution plan showing:
> Table pool/easer spool operation -
> Row Count: 9 M
> Disk i/o: 11k
> Row size: 1089
> Estimated cost: 11 k (57%)
> CPU cost: 3.3
> Sub tree cost: 20 K
> Any help/hint will be appreciated.
> Thanks,
> Alim
> ----
--
>
> FROM
> dbo.pds_txn T1
> INNER JOIN
> dbo.GROUPS T2 ON
> T1.GROUP_ID = T2.ID_200
> INNER JOIN
> dbo.DIVISIONS T3 ON
> T1.DIVISION = T3.ID_102
> INNER JOIN
> dbo.BILLING_AREAS T4 ON
> T1.BILLING_AREA = T4.ID_202
> INNER JOIN
> dbo.PROVIDERS T6 ON
> T1.PROVIDER = T6.ID_3
> INNER JOIN
> dbo.LOCATIONS T7 ON
> T1.LOCATION = T7.ID_100
> INNER JOIN
> dbo.PROCEDURES T8 ON
> T1.[PROCEDURE] = T8.ID_1
> INNER JOIN
> dbo.FSC T9 ON
> T1.ORIG_FSC = T9.ID_19
> INNER JOIN
> dbo.DIAGNOSIS T10 ON
> T1.TXN_DX_1 = T10.ID_36
> INNER JOIN
> dbo.pds_invoice T11 ON
> T1.INVOICE_NUM = T11.INVOICE_NUM AND
> T1.GROUP_ID = T11.GROUP_ID
> LEFT OUTER JOIN
> dbo.PROVIDERS T6A ON
> T11.PERFORMING_PHYS = T6A.ID_3
> WHERE
> T1.POSTING_PD_DTE >= '05/01/2003' AND
> T1.PAY_CODE = 21 AND
> T2.EXCLUSION_FLAG = 0 AND
> T3.DIV_NUM <> '2901'
>
>|||Alim,
Need to provide the table/index structure and the query that you are
trying to run..
Jayesh
"Leo Giakoumakis [MS]" <leogia_removethis_@.microsoft.com> wrote in messa
ge
news:e8OMTRyiGHA.3848@.TK2MSFTNGP04.phx.gbl...
> Hi Alim,
> It is hard to guess what the issue might be without more information.
> Could you attach the output of "statistics profile" or "statistics xml"
> (if you are using SQL Server 2005) ?
> Regards,
> Leo
>
> "alim" <alim@.discussions.microsoft.com> wrote in message
> news:3873F521-EEF2-4A62-9C66-00C035E1A9CD@.microsoft.com...
>

Friday, March 23, 2012

Joins

I want to convert the following statement:
SELECT E.Region, O.Instance_name, C.Disease_cat, C.Constraint_ref, M.Sex,
C.Sex_code, M.Age_start, M.Age_end, M.Age_range, SUM(M.Person_count) AS
Person_count, C.Conversion_factor, (SUM(M.Person_count))*C.Conversion_factor
FROM
Geo_definitions_normalised O LEFT OUTER JOIN
ICD_specifications_for_disease_ICD_9_ICD_10_calc_s pec_SPLIT C,
Geo_mortality_count_SPLIT M,
Experimental_parameters E
WHERE C.ICD_code = M.ICD
AND M.Cause BETWEEN C.ICD_start AND C.ICD_end_adjusted
AND M.Output_Area = O.Output_Area
AND O.Geo_category_class = E.Region
AND C.Sex_code_conversion = M.Sex
AND E.Region = @.region
AND E.Unique_identifier = @.Unique_identifier
GROUP BY /*O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex, M.Age_start, M.Age_end, M.Age_range, C.Sex_code,
C.Constraint_ref, C.Conversion_factor, M.Person_count
ORDER BY /* O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex, M.Age_start, M.Age_end, M.Age_range, C.Sex_code,
C.Constraint_ref, C.Conversion_factor, M.Person_count
into something like this:
SELECT /*O.Geo_category_class,*/ E.Region, O.Instance_name, C.Disease_cat,
C.Constraint_ref, M.Sex, C.Sex_code,
M.Age_start, M.Age_end, M.Age_range, SUM(M.Person_count) AS
Person_count, C.Conversion_factor, (SUM(M.Person_count))*C.Conversion_factor
FROM
Geo_definitions_normalised O LEFT OUTER JOIN
ICD_specifications_for_disease_ICD_9_ICD_10_calc_s pec_SPLIT C
JOIN Geo_mortality_count_SPLIT M
ON C.ICD_code = M.ICD AND M.Cause BETWEEN C.ICD_start AND
C.ICD_end_adjusted AND M.Output_Area = O.Output_Area AND
C.Sex_code_conversion = M.Sex
JOIN Experimental_parameters E
ON O.Geo_category_class = E.Region
WHERE E.Region = @.region AND E.Unique_identifier = @.Unique_identifier
GROUP BY /*O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex,
M.Age_start, M.Age_end, M.Age_range, C.Sex_code, C.Constraint_ref,
C.Conversion_factor, M.Person_count
ORDER BY E.Region, O.Instance_name, C.Disease_cat, M.Sex,
M.Age_start, M.Age_end, M.Age_range, C.Sex_code, C.Constraint_ref,
C.Conversion_factor, M.Person_count
But this does not work. I am trying to produce the same join as the first,
except that I want the outer join with the Geo_definitions_normalised table
Message posted via http://www.sqlmonster.com
Sorry, please replace the first statement with:
SELECT E.Region, O.Instance_name, C.Disease_cat, C.Constraint_ref, M.Sex,
C.Sex_code,
M.Age_start, M.Age_end, M.Age_range, SUM(M.Person_count) AS
Person_count, C.Conversion_factor, (SUM(M.Person_count))*C.Conversion_factor
FROM ICD_specifications_for_disease_ICD_9_ICD_10_calc_s pec_SPLIT C,
Geo_mortality_count_SPLIT M,
Geo_definitions_normalised O,
Experimental_parameters E
WHERE C.ICD_code = M.ICD
AND M.Cause BETWEEN C.ICD_start AND C.ICD_end_adjusted
AND M.Output_Area = O.Output_Area
AND O.Geo_category_class = E.Region
AND C.Sex_code_conversion = M.Sex
AND E.Region = @.region
AND E.Unique_identifier = @.Unique_identifier
GROUP BY /*O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex,
M.Age_start, M.Age_end, M.Age_range, C.Sex_code, C.Constraint_ref,
C.Conversion_factor, M.Person_count
ORDER BY /* O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex,
M.Age_start, M.Age_end, M.Age_range, C.Sex_code, C.Constraint_ref,
C.Conversion_factor, M.Person_count
Message posted via http://www.sqlmonster.com
sql

Joins

I want to convert the following statement:
SELECT E.Region, O.Instance_name, C.Disease_cat, C.Constraint_ref, M.Sex,
C.Sex_code, M.Age_start, M.Age_end, M.Age_range, SUM(M.Person_count) AS
Person_count, C.Conversion_factor, (SUM(M.Person_count))*C.Conversion_factor
FROM
Geo_definitions_normalised O LEFT OUTER JOIN
ICD_specifications_for_disease_ICD_9_ICD_10_calc_spec_SPLIT C,
Geo_mortality_count_SPLIT M,
Experimental_parameters E
WHERE C.ICD_code = M.ICD
AND M.Cause BETWEEN C.ICD_start AND C.ICD_end_adjusted
AND M.Output_Area = O.Output_Area
AND O.Geo_category_class = E.Region
AND C.Sex_code_conversion = M.Sex
AND E.Region = @.region
AND E.Unique_identifier = @.Unique_identifier
GROUP BY /*O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex, M.Age_start, M.Age_end, M.Age_range, C.Sex_code,
C.Constraint_ref, C.Conversion_factor, M.Person_count
ORDER BY /* O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex, M.Age_start, M.Age_end, M.Age_range, C.Sex_code,
C.Constraint_ref, C.Conversion_factor, M.Person_count
into something like this:
SELECT /*O.Geo_category_class,*/ E.Region, O.Instance_name, C.Disease_cat,
C.Constraint_ref, M.Sex, C.Sex_code,
M.Age_start, M.Age_end, M.Age_range, SUM(M.Person_count) AS
Person_count, C.Conversion_factor, (SUM(M.Person_count))*C.Conversion_factor
FROM
Geo_definitions_normalised O LEFT OUTER JOIN
ICD_specifications_for_disease_ICD_9_ICD_10_calc_spec_SPLIT C
JOIN Geo_mortality_count_SPLIT M
ON C.ICD_code = M.ICD AND M.Cause BETWEEN C.ICD_start AND
C.ICD_end_adjusted AND M.Output_Area = O.Output_Area AND
C.Sex_code_conversion = M.Sex
JOIN Experimental_parameters E
ON O.Geo_category_class = E.Region
WHERE E.Region = @.region AND E.Unique_identifier = @.Unique_identifier
GROUP BY /*O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex,
M.Age_start, M.Age_end, M.Age_range, C.Sex_code, C.Constraint_ref,
C.Conversion_factor, M.Person_count
ORDER BY E.Region, O.Instance_name, C.Disease_cat, M.Sex,
M.Age_start, M.Age_end, M.Age_range, C.Sex_code, C.Constraint_ref,
C.Conversion_factor, M.Person_count
But this does not work. I am trying to produce the same join as the first,
except that I want the outer join with the Geo_definitions_normalised table
--
Message posted via http://www.sqlmonster.comSorry, please replace the first statement with:
SELECT E.Region, O.Instance_name, C.Disease_cat, C.Constraint_ref, M.Sex,
C.Sex_code,
M.Age_start, M.Age_end, M.Age_range, SUM(M.Person_count) AS
Person_count, C.Conversion_factor, (SUM(M.Person_count))*C.Conversion_factor
FROM ICD_specifications_for_disease_ICD_9_ICD_10_calc_spec_SPLIT C,
Geo_mortality_count_SPLIT M,
Geo_definitions_normalised O,
Experimental_parameters E
WHERE C.ICD_code = M.ICD
AND M.Cause BETWEEN C.ICD_start AND C.ICD_end_adjusted
AND M.Output_Area = O.Output_Area
AND O.Geo_category_class = E.Region
AND C.Sex_code_conversion = M.Sex
AND E.Region = @.region
AND E.Unique_identifier = @.Unique_identifier
GROUP BY /*O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex,
M.Age_start, M.Age_end, M.Age_range, C.Sex_code, C.Constraint_ref,
C.Conversion_factor, M.Person_count
ORDER BY /* O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex,
M.Age_start, M.Age_end, M.Age_range, C.Sex_code, C.Constraint_ref,
C.Conversion_factor, M.Person_count
--
Message posted via http://www.sqlmonster.com

Joins

I want to convert the following statement:
SELECT E.Region, O.Instance_name, C.Disease_cat, C.Constraint_ref, M.Sex,
C.Sex_code, M.Age_start, M.Age_end, M.Age_range, SUM(M.Person_count) AS
Person_count, C.Conversion_factor, (SUM(M.Person_count))*C.Conversion_factor
FROM
Geo_definitions_normalised O LEFT OUTER JOIN
ICD_specifications_for_disease_ICD_9_ICD
_10_calc_spec_SPLIT C,
Geo_mortality_count_SPLIT M,
Experimental_parameters E
WHERE C.ICD_code = M.ICD
AND M.Cause BETWEEN C.ICD_start AND C.ICD_end_adjusted
AND M.Output_Area = O.Output_Area
AND O.Geo_category_class = E.Region
AND C.Sex_code_conversion = M.Sex
AND E.Region = @.region
AND E.Unique_identifier = @.Unique_identifier
GROUP BY /*O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex, M.Age_start, M.Age_end, M.Age_range, C.Sex_code,
C.Constraint_ref, C.Conversion_factor, M.Person_count
ORDER BY /* O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex, M.Age_start, M.Age_end, M.Age_range, C.Sex_code,
C.Constraint_ref, C.Conversion_factor, M.Person_count
into something like this:
SELECT /*O.Geo_category_class,*/ E.Region, O.Instance_name, C.Disease_cat,
C.Constraint_ref, M.Sex, C.Sex_code,
M.Age_start, M.Age_end, M.Age_range, SUM(M.Person_count) AS
Person_count, C.Conversion_factor, (SUM(M.Person_count))*C.Conversion_factor
FROM
Geo_definitions_normalised O LEFT OUTER JOIN
ICD_specifications_for_disease_ICD_9_ICD
_10_calc_spec_SPLIT C
JOIN Geo_mortality_count_SPLIT M
ON C.ICD_code = M.ICD AND M.Cause BETWEEN C.ICD_start AND
C.ICD_end_adjusted AND M.Output_Area = O.Output_Area AND
C.Sex_code_conversion = M.Sex
JOIN Experimental_parameters E
ON O.Geo_category_class = E.Region
WHERE E.Region = @.region AND E.Unique_identifier = @.Unique_identifier
GROUP BY /*O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex,
M.Age_start, M.Age_end, M.Age_range, C.Sex_code, C.Constraint_ref,
C.Conversion_factor, M.Person_count
ORDER BY E.Region, O.Instance_name, C.Disease_cat, M.Sex,
M.Age_start, M.Age_end, M.Age_range, C.Sex_code, C.Constraint_ref,
C.Conversion_factor, M.Person_count
But this does not work. I am trying to produce the same join as the first,
except that I want the outer join with the Geo_definitions_normalised table
Message posted via http://www.droptable.comSorry, please replace the first statement with:
SELECT E.Region, O.Instance_name, C.Disease_cat, C.Constraint_ref, M.Sex,
C.Sex_code,
M.Age_start, M.Age_end, M.Age_range, SUM(M.Person_count) AS
Person_count, C.Conversion_factor, (SUM(M.Person_count))*C.Conversion_factor
FROM ICD_specifications_for_disease_ICD_9_ICD
_10_calc_spec_SPLIT C,
Geo_mortality_count_SPLIT M,
Geo_definitions_normalised O,
Experimental_parameters E
WHERE C.ICD_code = M.ICD
AND M.Cause BETWEEN C.ICD_start AND C.ICD_end_adjusted
AND M.Output_Area = O.Output_Area
AND O.Geo_category_class = E.Region
AND C.Sex_code_conversion = M.Sex
AND E.Region = @.region
AND E.Unique_identifier = @.Unique_identifier
GROUP BY /*O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex,
M.Age_start, M.Age_end, M.Age_range, C.Sex_code, C.Constraint_ref,
C.Conversion_factor, M.Person_count
ORDER BY /* O.Geo_category_class, */E.Region, O.Instance_name,
C.Disease_cat, M.Sex,
M.Age_start, M.Age_end, M.Age_range, C.Sex_code, C.Constraint_ref,
C.Conversion_factor, M.Person_count
Message posted via http://www.droptable.com

joins

Hi Friends
I need ur advise on this one.
when writing sql statements and whenever there is need to join 2 or more tables am used to the following syntax (using WHERE to join tables)

select a.name,b.code from table a,table b where a.code=b.code

as you all know we can also use INNER JOINS,OUTER JOINS etc., to join tables and all BOL help example contains this type of syntax.

my question is , am having difficulty using/writing this syntax in my queries .meaning uysing left joins,inner joins in the same queries.I appreciate if u guys can direct me to some good articles or that sort of thing to improve my understanding of this type of syntax.
Thanks

Hi,

IMHO, the information you need is in BOL. As you have mentioned, it contains samples perjorming JOIN querries. All you have to do is experiment with it to get the idea behind it. Use Query Analyzer to achieve this.

cheers,

Paul June A. Domag

|||

See if these help:

--inner join
select a.name,b.code
from table a inner join table b on a.code=b.code

--left join
select a.name,b.code
from table a left join table b on a.code=b.code

--right join
select a.name,b.code
from table a right join table b on a.code=b.code

--full join
select a.name,b.code
from table a full join table b on a.code=b.code

--cross join
select a.name,b.code
from table a cross join table b

|||See if this helps:
http://www.firstsql.com/tutor.htm and especially this http://www.firstsql.com/tutor3.htm#join
--
Frank Kalis
Microsoft SQL Server MVP
http://www.insidesql.de
Ich unterstütze PASS Deutschland e.V. (http://www.sqlpass.de)|||Thanks Frank.That helps mate Smile|||

Hi Paul

Seems like you are very helpful.........

Please assist.

i have several document groups in a table which data i want to export. my statement is: select * from docs_indexed where di_doc_group = 71. this is working and i get the correct results. problem is, i have 350 doc_groups. how do i create a query where i can get results for all the doc_groups in one query?

Regards

Hannes

joins

Hi Friends
I need ur advise on this one.
when writing sql statements and whenever there is need to join 2 or more tables am used to the following syntax (using WHERE to join tables)

select a.name,b.code from table a,table b where a.code=b.code

as you all know we can also use INNER JOINS,OUTER JOINS etc., to join tables and all BOL help example contains this type of syntax.

my question is , am having difficulty using/writing this syntax in my queries .meaning uysing left joins,inner joins in the same queries.I appreciate if u guys can direct me to some good articles or that sort of thing to improve my understanding of this type of syntax.
Thanks

Hi,

IMHO, the information you need is in BOL. As you have mentioned, it contains samples perjorming JOIN querries. All you have to do is experiment with it to get the idea behind it. Use Query Analyzer to achieve this.

cheers,

Paul June A. Domag

|||

See if these help:

--inner join
select a.name,b.code
from table a inner join table b on a.code=b.code

--left join
select a.name,b.code
from table a left join table b on a.code=b.code

--right join
select a.name,b.code
from table a right join table b on a.code=b.code

--full join
select a.name,b.code
from table a full join table b on a.code=b.code

--cross join
select a.name,b.code
from table a cross join table b

|||See if this helps:
http://www.firstsql.com/tutor.htm and especially this http://www.firstsql.com/tutor3.htm#join
--
Frank Kalis
Microsoft SQL Server MVP
http://www.insidesql.de
Ich unterstütze PASS Deutschland e.V. (http://www.sqlpass.de)
|||Thanks Frank.That helps mate Smile|||

Hi Paul

Seems like you are very helpful.........

Please assist.

i have several document groups in a table which data i want to export. my statement is: select * from docs_indexed where di_doc_group = 71. this is working and i get the correct results. problem is, i have 350 doc_groups. how do i create a query where i can get results for all the doc_groups in one query?

Regards

Hannes

Wednesday, March 21, 2012

Joining two fields to single field

If I have a database table with the following columns:
ID
Other_ID
Description

And I want to join the two ID fields to one field in another table that contains the following fields:
ID
Name

How would i do that?

Here is some sample data and what I would like returned

TABLE1

ID Other_ID Description
row 1 1 2 Number1
row 2 3 1 Number2

TABLE2

ID Name
row 1 1 John
row 2 2 Bob
row 3 3 Bill

I want to query TABLE1, row 1 so that I pull back the Names for the values stored in the ID and Other_ID fields so that my results are like:
John Bob Number1

The only way around it now is that I store Other_Name in Table1.

Thanks.

try this

select (select name from Table2 t2 where t1.id=t2.id) ,
(select name from Table2 t2 where t1.Other_id=t2.id) ,Description
from Table1 t1|||

I'll take a stab at it:

SELECT T2.Name as Name1, T3.Name as Name2, Description FROM TABLE1 INNER JOIN TABLE2 AS T2 ON TABLE1.ID=T2.ID INNER JOIN TABLE2 AS T3 ON TABLE1.Other_ID=T3.ID

|||Thanks. This worked great.sql

Joining two columns together to be searched as one

Hi all,

I have three questions to ask that hopefully can be answered. My database server is MySQL 4.1 and my database table contains the following example data:

Id | Store | Make | Model | Price
----------------
1 | Store1 | JVC | AV36D502 | 100.00
2 | Store2 | JVC | AV36D502 | 400.00
3 | Store1 | Panasonic | CT32HX41 | 250.00
4 | Store2 | Panasonic | CT32HX41 | 350.00
5 | Store1 | Sony | KV32S42 | 400.00
6 | Store2 | Sony | KV32S42 | 500.00

(1) Is it possibe to have in my select statement the following: "WHERE ((Make, Model) = 'Sony KV32S42')", I have already tried this but it throws up errors. What I'm trying to do is to some how join together the Make and Model columns and then to see if it matches the search term.

(2) If I was to "SELECT DISTINCT Make" or equivalent, rather than returning 3 rows is there anyway to return just the one row but with the value of "JVC Panasonic Sony" i.e. a string of all Makes, or is this impossible.

and (3) I have another select statement "SELECT DISTINCT Make, MIN(Price), MAX(Price)" with the output shown below. If I "ORDER BY Price ASC" the default is that it orders it by the maximum price, what I want to do is to order it by the minimum price only. "ORDER BY MIN(Price) ASC" has errors or again is this impossible.

Make | MIN(Price) | MAX(Price)
------------
JVC | 100.00 | 400.00
Panasonic | 250.00 | 350.00
Sony | 400.00 | 500.00

I know I'm asking a lot but again I just can't find any good information on the net. Thanking you in advance.(1) where concat_ws(' ',make.model) = 'Sony KV32S42'

(2) with the GROUP_CONCAT function

(3) you can't use DISTINCT here

select Make, MIN(Price) as minprice, MAX(Price) as maxprice
from yourtable group by Make order by minprice|||(1) WHERE make = 'Sony' AND model = 'KV32S42'.
(2) AFAIK, this is impossible with "standard" SQL.
(3) See r937's solution, or alternatively "ORDER BY 2".|||Many thanks guys,

(1) and (3) work perfectly now, (2) will work once I upgrade to mySQL 4.1 or 5.0|||btw, your design is denormalized... Is there a reason you don't store make and model in a seperate table?|||I'm sorry I don't understand, why would you want to put make and model in seperate tables, surely that would make the design more complex? Or would it be better (more efficient) if I just had the one column called "product" which would store the make and model, i.e. Sony KV32S42.|||It would make the model slighly more "complex" in that you will have an extra table, sure. However it will make the model much simpler in that you will have far more flexibility with a "normalized" design. Read up at this site (http://r937.com/relational.html). It has some good models for what I'm talking about.

You do have the right general idea though. If you were to put make and model in a seperate table with a unique key, you could then use that key to store prices for competitors. When it comes time to report, your queries become far easier and more intuitive, with less margin for error.

Joining three tables

G'day,
I have got following 4 tables

Table 1
name age city

jack 20 Melbourne
Nick 30 Bendigo
Russ 28 Sydney

Table 2
name age city Company

jack 20 Melbourne AAA
Nick 30 Bendigo BBB
Russ 28 Sydney AAA
Marty 31 Perth AAA

Table 3

name age city Position

jack 20 Melbourne Manager
Nick 30 Bendigo Manager
Russ 28 Sydney Clerk
Marty 31 Perth Manager

Table 4

name age city datejoined

jack 20 Melbourne 09-09-2001
Nick 30 Bendigo 08-05-2001
Russ 28 Sydney 10-12-2000
Marty 31 Perth 11-11-1999

I want a query which extract the name, age and city from Table 2 (where name,age and city equals table1 values) and position from table3 where position is 'manager' else return null and date joined from table 4 only for the managers else return null.

so the result should be

name age city position datejoined

jack 20 Melbourne Manager 09-09-2001
Nick 30 Bendigo Manager 08-05-2001
Russ 28 Sydney null null

my query

SELECT b. name, b.age, b.city,b.company,c.position,d.datejoined
FROM Table1 a, Table2 b, Table3 c, Table4 d
WHERE
a.age=b.age
and a.name=b.name
and a.city=b.city
and b.age*=c.age
and b.name*=c.name
and b.city*=c.city
and b.position='Manager'
and b.age*=d.age
and b.name*=d.name
and b.city*=d.city

THE RESULT IS

jack 20 Melbourne Manager 09-09-2001
Nick 30 Bendigo Manager 08-05-2001
Russ 28 Sydney null 10-12-2000

When I try to join table4 with table i am getting a exception

Ps: as the original code was in SQL SERVER 6.5 I have to use *= for joins not keywords LEFT JOIN or RIGHT JOIN

hope yo guys can help me

regards
Melbto solve it your way gives me a headache...so

here is my alternate solution
combine all of the tables into one table

name age city position company datejoined
joe 20 melbourne manager xyz co. 8/15/2000

this would move you up to at least 2NF
then add a primary key to uniquely identify the entity
such as employeeid or EmpId
then add a column called ReportsTO

empid name age city position company datejoined reportsto
1 joe 20 melbourne manager xyz co. 8/15/2000 1
2 mary 25 perth stooge xyz co. 10/15/2003 1
3 steve 25 perth stooge xyz co. 11/15/2003 2

then join the table to itself.

select name, age, city, position, company, datejoined
from tablea as TA join tablea as TB
on ta.reportsto = TB.empid
where position = 'manager'

check out the employees table in northwind for the direct example.
and ps
always set the top most employee's reportsto column eaqual to that employees own empid
this eliminates the need for an outer join in the self join.|||Look, here's the logic required. Translate it into archaic WHERE joins if you must...

select table1.name, table1.age, table1.city, table2.Company, table3.Position, table4.datejoined
from table1
inner join table2
on table1.name = table2.name
and table1.age = table2.age
and table1.city = table2.city
left outer join table3
on table1.name = table3.name
and table1.age = table3.age
and table1.city = table3.city
and table3.Position = 'Manager'
left outer join table4
on table3.name = table4.name
and table3.age = table4.age
and table3.city = table4.city

...but I gotta tell you this is one screwed up table structure. Not only is far from normalized, but FirstName/Age/City as a composite primary key?|||Man, once the original question reached the end of the screen I lost track and interest...But for Codd's sake, I hope the designer of this database is in prison by now for systems analysis and database design fraud!|||ease up guys

that table structure is in 5th normal form

the only thing it doesn't do is utilize surrogate keys, and that in itself is not a crime

assuming table 1 has a composite primary key, then tables 2, 3, and 4 are single value attribute tables

notice that in this design, nulls are not required, so that if if a given person doesn't have a company, position, or date joined, then there won't be a row for that person in the associated table

perfectly valid design, and you can ask the guys at dbdebumph.com to verify this

not that you'd ever catch me creating a design like this, because, unlike the guys at dbdebumph.com, i *heart* nulls

the complex left outer joins is a perfect example of why this type of design sucks

yes, it's an egregiously impractical design, but from a normalization point of view, it is fine

normalization does not mean "remove primary key redundancy across tables by implementing surrogate keys if you can"

normalization has to do with the dependency of non-key attributes on the primary key and on interdependence on non-key attributes

disclaimer: i'm not 100% certain about it being 5th normal, maybe it's only 4th normal, but i know it's higher than 3rd|||Come ON, Rudy, how can you say that NAME, CITY, and AGE be perfect for a primary key?????? I HAVE to go with BLindman's comment on that!!!!!!|||now here is a perfect example of contradictory motives and operations

it is entirely possible to assume as most of us did that this was de-normalized data, and not a fully realized model.
however the "glass is half full" crowd have decided that this example is so far along in it's design that it is close to the idiot savant stage.

our motive to achieve cleanliness in our data design can sometimes cause us to chase operations that contradict common sense.

so it seems that it is entirely possible to follow the Rules just so far that you actually break all of the rules.

this is why i consider normalization to be a good GUIDELINE but not a hard and fast rule. i have always maintained that it is the business model that is being exposed by appropriately identifying the business rules that govern the company. and accurately define the data model as well
or simply business drives data.

Scott Davis
"If I'm curt with you, it's because time is a factor here. I think fast, I talk fast, and I need you guys to act fast if you want to get out of this. So, pretty please - with sugar on top..." Mr. Wolf|||Come ON, Rudy, how can you say that NAME, CITY, and AGE be perfect for a primary key?????? I HAVE to go with BLindman's comment on that!!!!!!did i say it was a perfect primary key? no, i said it was a perfectly valid design

and which comment of blindman's are you going with?

if it's "screwed up table structure" then maybe i agree, because as we all seem to realize, a structure using a surrogate key might be a lot better

but if the comment you go with is "far from normalized" then you are wrong

like i suggested, you guys need to look up the definition of the normal forms before you start claiming something is not normalized|||Thanks guys
Have compromised the DB designer and have recreated the tables in different format.

cheers
Melb|||Rudy, I never said the design was "far from normalized", I just said that I ho[ped the designer was somehow prosecuted for DBA fraud, or something like that!

I KNOW you know what you're talking about, but I hope the guy (poster) drew a lesson from all this, that's all (hands up, hoping for being released to the family for database police cooperation) ;)|||Rudy, I never said the design was "far from normalizedi know you didn't, but blindman did, and you said you "have to go with [his] comment"

:)|||OK, what I refered to was this:but FirstName/Age/City as a composite primary key?|||And BTW, this combination CANNOT POSSIBLY YIELD a unique primary key, which means the design ain't worth you know what either...you know?|||what do you mean, "CANNOT POSSIBLY YIELD a unique primary key"??

of course it can

it's not very practical, but it is most certainly possible

Joining tables in several ways withing the same query

We have an appointment and scheduling application with the following
structure:
Appointments - a table containing appointment information;
Phonebook - a table containing information about people;
Users - a table with a foreign key to Phonebook, defining specific
Phonebook entries as system users.
The table Appointments is linked many-to-many, via a junction table, to
Phonebook, determining the participants in an appointment. Is is also
linked, through a second junction table, to Users, determining the
appointment participants who are system users (and can therefore change
details of the meeting, accept/decline their participation, etc).
My questions is: We retrieve details about meetings (basically a daily
calendar display) using one query, joining the different tables
mentioned above. Since participant's names all come from Phonebook, how
can I, in the query's result set, distinguish system participants from
other participants? Although they are joined into the result set
through two different tables, they all end up as one field.
Any advice will be appreciated :)Hi
Try using UNIONs. If you are not comfortable in using them, please send the
DDL so that any one can post a query to you.
--
best Regards,
Chandra
http://chanduas.blogspot.com/
http://groups.msn.com/SQLResource/
---
"hsifelbmur" wrote:
> We have an appointment and scheduling application with the following
> structure:
> Appointments - a table containing appointment information;
> Phonebook - a table containing information about people;
> Users - a table with a foreign key to Phonebook, defining specific
> Phonebook entries as system users.
> The table Appointments is linked many-to-many, via a junction table, to
> Phonebook, determining the participants in an appointment. Is is also
> linked, through a second junction table, to Users, determining the
> appointment participants who are system users (and can therefore change
> details of the meeting, accept/decline their participation, etc).
> My questions is: We retrieve details about meetings (basically a daily
> calendar display) using one query, joining the different tables
> mentioned above. Since participant's names all come from Phonebook, how
> can I, in the query's result set, distinguish system participants from
> other participants? Although they are joined into the result set
> through two different tables, they all end up as one field.
> Any advice will be appreciated :)
>|||You can reference 2 different copies of the same table in a query via an
alias. You didn't post DDL, so I'll use the Employees table in Northwind.
Here, you want the employee name and manager name:
select
e.LastName Employee
, m.LastName Manager
from
dbo.Employees e
join dbo.Employees m on m.EmployeeID = e.ReportsTo
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
.
"hsifelbmur" <aquarian1978@.yahoo.com> wrote in message
news:1116225930.258119.295960@.g43g2000cwa.googlegroups.com...
We have an appointment and scheduling application with the following
structure:
Appointments - a table containing appointment information;
Phonebook - a table containing information about people;
Users - a table with a foreign key to Phonebook, defining specific
Phonebook entries as system users.
The table Appointments is linked many-to-many, via a junction table, to
Phonebook, determining the participants in an appointment. Is is also
linked, through a second junction table, to Users, determining the
appointment participants who are system users (and can therefore change
details of the meeting, accept/decline their participation, etc).
My questions is: We retrieve details about meetings (basically a daily
calendar display) using one query, joining the different tables
mentioned above. Since participant's names all come from Phonebook, how
can I, in the query's result set, distinguish system participants from
other participants? Although they are joined into the result set
through two different tables, they all end up as one field.
Any advice will be appreciated :)

Joining tables

Can someone please advise how i join the following two tables:
I want to left join on dt,Category and subcategory from Table 1
Table 1:
SELECT TOP 100 PERCENT Y, M, Category, SubCategory,dt
FROM (SELECT dbo.tblCalendar_jp.dt, dbo.tblCalendar_jp.Y,
dbo.tblCalendar_jp.M, dbo.TblRetrospectiveDiary.SubCategory,
dbo.TblRetrospectiveDiary.Category
FROM dbo.tblCalendar_jp CROSS JOIN
dbo.TblRetrospectiveDiary
WHERE (dbo.tblCalendar_jp.FY = 2005)) calrd
GROUP BY Y, M, Category, SubCategory
ORDER BY Y, M
Table 2:
SELECT Category, SubCategory, dt, [Time]
FROM (SELECT Category, SubCategory, LEFT(DateFrom, 11) AS dt,
DateTo, DATEDIFF(mi, DateFrom, DateTo) AS [Time]
FROM dbo.TblRetrospectiveDiary) rd
Thanks in anticipationjust a hint
SELECT TOP 100 PERCENT Y, M, Category, SubCategory,dt
FROM (SELECT dbo.tblCalendar_jp.dt, dbo.tblCalendar_jp.Y,
dbo.tblCalendar_jp.M, dbo.TblRetrospectiveDiary.SubCategory,
dbo.TblRetrospectiveDiary.Category
FROM dbo.tblCalendar_jp CROSS JOIN
dbo.TblRetrospectiveDiary
-->> stop here
join -- this is the join
(
SELECT Category, SubCategory, dt, [Time]
FROM (SELECT Category, SubCategory, LEFT(DateFrom, 11) AS dt,
DateTo, DATEDIFF(mi, DateFrom, DateTo) AS [Time]
FROM dbo.TblRetrospectiveDiary) rd
) as a
on
-- join statement here use "a" as alias of 2nd query
--continueing statement from Q1
WHERE (dbo.tblCalendar_jp.FY = 2005)) calrd
GROUP BY Y, M, Category, SubCategory --include the other fields in the
select list
ORDER BY Y, M
thanks,
Jose de Jesus Jr. Mcp,Mcdba
Data Architect
Sykes Asia (Manila philippines)
MCP #2324787
"Keith Rudd" wrote:

> Can someone please advise how i join the following two tables:
> I want to left join on dt,Category and subcategory from Table 1
> Table 1:
> SELECT TOP 100 PERCENT Y, M, Category, SubCategory,dt
> FROM (SELECT dbo.tblCalendar_jp.dt, dbo.tblCalendar_jp.Y,
> dbo.tblCalendar_jp.M, dbo.TblRetrospectiveDiary.SubCategory,
> dbo.TblRetrospectiveDiary.Ca
tegory
> FROM dbo.tblCalendar_jp CROSS JOIN
> dbo.TblRetrospectiveDiary
> WHERE (dbo.tblCalendar_jp.FY = 2005)) calrd
> GROUP BY Y, M, Category, SubCategory
> ORDER BY Y, M
>
> Table 2:
> SELECT Category, SubCategory, dt, [Time]
> FROM (SELECT Category, SubCategory, LEFT(DateFrom, 11) AS dt,
> DateTo, DATEDIFF(mi, DateFrom, DateTo) AS [Time]
> FROM dbo.TblRetrospectiveDiary) rd
> Thanks in anticipation
>
>

Monday, March 19, 2012

Joining Rows in a SubQuery

I have the following code in a stored procedure
SELECT CatID, ParentId, CategoryName, (select count(*)
from members WHERE DirectoryCat = DirectoryCats.CatID and
InFreeDirectory=1 and ApproveDirectory=1) pagecount
FROM DirectoryCats
where active=1
order by CategoryName
it's output is similar to this:
CatID | ParentId | CategoryName | pagecount
6 1 Cat1 0
4 Null Cat2 3
I would like to make a new column (say Newtext) adn Return something like th
is
CatID | ParentId | CategoryName | pagecount | NewText
6 1 Cat1 0 Cat1 (0)
4 Null Cat2 3 Cat2 (3)
How can i join the data to have this result?
I would hope that i could do something like CategoryName + "(" + pagecount +
")" in some sort of sql statement.
Thanks for any input
Lots of ways, here's one
SELECT CatID, ParentId, CategoryName,pagecount ,
CategoryName + '(' + cast(pagecount as varchar(10))+ ')' as
NewText
FROM
(
SELECT CatID, ParentId, CategoryName, (select count(*)
from members WHERE DirectoryCat = DirectoryCats.CatID and
InFreeDirectory=1 and ApproveDirectory=1) pagecount
FROM DirectoryCats
where active=1
) X
order by CategoryName|||One approach is to use a derived table, embedding the existing query
in the FROM clause of an outer query:
SELECT *,
NewText =
CategoryName + '(' + convert(varchar(8),pagecount) + ')'
FROM (<query as you stated it> ) as X
Roy Harvey
Beacon Falls, CT
On Thu, 27 Apr 2006 13:37:02 -0700, Fabuloussites
<Fabuloussites@.discussions.microsoft.com> wrote:

>I have the following code in a stored procedure
>SELECT CatID, ParentId, CategoryName, (select count(*)
>from members WHERE DirectoryCat = DirectoryCats.CatID and
>InFreeDirectory=1 and ApproveDirectory=1) pagecount
>FROM DirectoryCats
>where active=1
>order by CategoryName
>
>it's output is similar to this:
>CatID | ParentId | CategoryName | pagecount
>6 1 Cat1 0
>4 Null Cat2 3
>I would like to make a new column (say Newtext) adn Return something like t
his
>CatID | ParentId | CategoryName | pagecount | NewText
>6 1 Cat1 0 Cat1 (0)
>4 Null Cat2 3 Cat2 (3)
>How can i join the data to have this result?
>I would hope that i could do something like CategoryName + "(" + pagecount
+
>")" in some sort of sql statement.
>Thanks for any input|||thanks for the fast and helpful response.
"markc600@.hotmail.com" wrote:

>
> Lots of ways, here's one
>
> SELECT CatID, ParentId, CategoryName,pagecount ,
> CategoryName + '(' + cast(pagecount as varchar(10))+ ')' as
> NewText
> FROM
> (
> SELECT CatID, ParentId, CategoryName, (select count(*)
> from members WHERE DirectoryCat = DirectoryCats.CatID and
> InFreeDirectory=1 and ApproveDirectory=1) pagecount
> FROM DirectoryCats
> where active=1
> ) X
> order by CategoryName
>|||thanks for the fast and helpful response.
"Roy Harvey" wrote:

> One approach is to use a derived table, embedding the existing query
> in the FROM clause of an outer query:
> SELECT *,
> NewText =
> CategoryName + '(' + convert(varchar(8),pagecount) + ')'
> FROM (<query as you stated it> ) as X
> Roy Harvey
> Beacon Falls, CT
>
> On Thu, 27 Apr 2006 13:37:02 -0700, Fabuloussites
> <Fabuloussites@.discussions.microsoft.com> wrote:
>
>