Sql query data horizontally with sum and condition in a row
I am trying to get data from the following query in a row with total but not succeed and getting error message. Please help and advise.
Select empid,name,country,
sum(case category when 'JOB' then sum(core+RR) else 0 end) as 'JOB-Sum',
sum(case category when 'PRIVATE' then sum(core+PP) else 0 end) as 'PRIVATE-Sum',
group by empid,name,country
Note: Following query is good for getting result in one row but i have to put sum calculation with 'THEN' and want result in a row.
SELECT ID, MAX(case when Col1 = 'Yes' then 1 else 0 end) AS Col1,
MAX(case when Col2 = 'Yes' then 1 else 0 end) AS Col2
FROM MyTable
GROUP BY ID
Please show some sample data and expected output.
Regards,
Rob.
Similar Messages
-
Sql query slowness due to rank and columns with null values:
Sql query slowness due to rank and columns with null values:
I have the following table in database with around 10 millions records:
Declaration:
create table PropertyOwners (
[Key] int not null primary key,
PropertyKey int not null,
BoughtDate DateTime,
OwnerKey int null,
GroupKey int null
go
[Key] is primary key and combination of PropertyKey, BoughtDate, OwnerKey and GroupKey is unique.
With the following index:
CREATE NONCLUSTERED INDEX [IX_PropertyOwners] ON [dbo].[PropertyOwners]
[PropertyKey] ASC,
[BoughtDate] DESC,
[OwnerKey] DESC,
[GroupKey] DESC
go
Description of the case:
For single BoughtDate one property can belong to multiple owners or single group, for single record there can either be OwnerKey or GroupKey but not both so one of them will be null for each record. I am trying to retrieve the data from the table using
following query for the OwnerKey. If there are same property rows for owners and group at the same time than the rows having OwnerKey with be preferred, that is why I am using "OwnerKey desc" in Rank function.
declare @ownerKey int = 40000
select PropertyKey, BoughtDate, OwnerKey, GroupKey
from (
select PropertyKey, BoughtDate, OwnerKey, GroupKey,
RANK() over (partition by PropertyKey order by BoughtDate desc, OwnerKey desc, GroupKey desc) as [Rank]
from PropertyOwners
) as result
where result.[Rank]=1 and result.[OwnerKey]=@ownerKey
It is taking 2-3 seconds to get the records which is too slow, similar time it is taking as I try to get the records using the GroupKey. But when I tried to get the records for the PropertyKey with the same query, it is executing in 10 milliseconds.
May be the slowness is due to as OwnerKey/GroupKey in the table can be null and sql server in unable to index it. I have also tried to use the Indexed view to pre ranked them but I can't use it in my query as Rank function is not supported in indexed
view.
Please note this table is updated once a day and using Sql Server 2008 R2. Any help will be greatly appreciated.create table #result (PropertyKey int not null, BoughtDate datetime, OwnerKey int null, GroupKey int null, [Rank] int not null)Create index idx ON #result(OwnerKey ,rnk)
insert into #result(PropertyKey, BoughtDate, OwnerKey, GroupKey, [Rank])
select PropertyKey, BoughtDate, OwnerKey, GroupKey,
RANK() over (partition by PropertyKey order by BoughtDate desc, OwnerKey desc, GroupKey desc) as [Rank]
from PropertyOwners
go
declare @ownerKey int = 1
select PropertyKey, BoughtDate, OwnerKey, GroupKey
from #result as result
where result.[Rank]=1
and result.[OwnerKey]=@ownerKey
go
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
With clause in SQL query data model
Hello!
isn't it possible to use the with clause in sql query data models?
for example following query:
WITH
a_test as (
select dummy from dual
select *
from a_test
brings up a "XML Parsing Error: no element found"-error...
BR PaulI tried a slightly different query (see below) and the query worked fine and retrieved data.. I did not get any errors.
WITH
a_test as (
select 'dummy' from dual
select *
from a_test
This works as well.. retrieving the value of the parameter
WITH
a_test as (
select :Test_ID from dual
select *
from a_test
thanks,
BIPuser -
Different LOV behavior between SQL query data model and data template
I have noticed different behavior when using parameters linked to list of values (LOV) of type menu with the multiple selection option enabled and a SQL query data model vs a data template. Here's the example because that first sentence was probably really confusing.
SQL Query:
select
plmc.MonthCode, plmc.ModalityDim, plmc.ModalityName,plmc.RegionDim
from
DataOut.dbo.PatientLabMonthlyCross plmc
where
plmc.MonthCode = 200202
and plmc.RegionDim = 1209
and 1 =
case
when coalesce(:modalityDim,null) is null
then 1
else
case
when plmc.ModalityDim in (:modalityDim)
then 1
else 0
end
end
Putting BI Publisher into debug mode, defining a data model of type SQL Query, defining a parameter called :modalityDim linked to a LOV that allows multiple selections, and selecting a couple of values from the LOV the output of the prepared statement is:
[081607_122647956][][STATEMENT] Sql Query : select
plmc.MonthCode,
plmc.ModalityDim,
plmc.ModalityName,
plmc.RegionDim
from
DataOut.dbo.PatientLabMonthlyCross plmc
where
plmc.MonthCode = 200202
and plmc.RegionDim = 1209
and 1 =
case
when coalesce(?,?,null) is null
then 1
else
case
when plmc.ModalityDim in (?,?)
then 1
else 0
end
end
[081607_122647956][][STATEMENT] 1:6
[081607_122647956][][STATEMENT] 2:7
[081607_122647956][][STATEMENT] 3:6
[081607_122647956][][STATEMENT] 4:7
[081607_122654713][][EVENT] Data Generation Completed...
[081607_122654713][][EVENT] Total Data Generation Time 7.0 seconds
Note how the bind variable :modalityDim was changed into two parameters in the prepared statement.
When I use this same SQL Query in a data template the output is:
[081607_012113018][][STATEMENT] Sql Query : select
plmc.MonthCode,
plmc.ModalityDim,
plmc.ModalityName,
plmc.RegionDim
from
DataOut.dbo.PatientLabMonthlyCross plmc
where
plmc.MonthCode = 200202
and plmc.RegionDim = 1209
and 1 =
case
when coalesce(?,null) is null
then 1
else
case
when plmc.ModalityDim in (?)
then 1
else 0
end
end
[081607_012113018][][STATEMENT] 1:'6','7'
[081607_012113018][][STATEMENT] 2:'6','7'
[081607_012113574][][EXCEPTION] java.sql.SQLException: Syntax error converting the nvarchar value ''6','7'' to a column of data type int.
Note the exception because it is trying to convert the multiple parameter values.
Am I doing something completely wrong here? I really need to use a data template because I will need to link a couple of queries together from different database vendors.
-markThis is for 10.1.3.4 - because in 11g every SQL query is automatially part of a data model.
In 10g SQL query is for simple unrelated SQL queries.
If you need to use advance features such as:
a) multiple SQL queries that are joined in master-detail relation ships
b) before/after report triggers
Then you will need to use the data template, which is an XML description
of the queries, links, and PL/SQL calls.
hope that helps,
Klaus -
CAML Query with 10 AND conditions
Hello,
I need some help with a CAML query. This particular query needs to have 10 AND conditions. Quite frankly, with all the nesting it is driving me a little nuts:
What I have is:
<Query>
<Where>
<And>
<And>
<And>
<And>
<And>
<And>
<And>
<And>
<And>
<Eq><FieldRef Name='Column1' LookupId='TRUE' /><Value Type='Text'>10341</Value></Eq>
<Eq><FieldRef Name='Column2' LookupId='TRUE' /><Value Type='Text'>9539</Value></Eq>
</And>
<Eq><FieldRef Name='Column3' LookupId='TRUE' /><Value Type='Text'>183</Value></Eq>
</And>
<Eq><FieldRef Name='Column4' LookupId='TRUE' /><Value Type='Text'>35</Value></Eq>
</And>
<IsNull><FieldRef Name='Column5' /></IsNull>
</And>
<Eq><FieldRef Name='Column6' LookupId='TRUE' /><Value Type='Text'>4387</Value></Eq>
</And>
<Eq><FieldRef Name='Column7' LookupId='TRUE' /><Value Type='Text'>4204</Value></Eq>
</And>
<Eq><FieldRef Name='Column8' LookupId='TRUE' /><Value Type='Text'>36</Value></Eq>
</And>
<Eq><FieldRef Name='Column9' LookupId='TRUE' /><Value Type='Text'>213</Value></Eq>
</And>
<IsNull><FieldRef Name='Column10' /></IsNull>
</And>
</Where>
</Query>
I have added this into my ItemAdding Event Receiver as it will basically do a check for duplicate items based on the 10 columns.
If anyone can help guide me in this, it would be much appreciated. I have been using a CAML Query Builder to help.http://webcache.googleusercontent.com/search?q=cache:xji7jOxa5_EJ:aasai-sharepoint.blogspot.com/2013/02/caml-query-with-multiple-conditions.html+&cd=3&hl=en&ct=clnk&gl=in
http://stackoverflow.com/questions/6203821/caml-query-with-nested-ands-and-ors-for-multiple-fields
Since you are not allowed to put more than two conditions in one condition group (And | Or) you have to create an extra nested group (MSDN). The expression
A AND B AND C looks like this:
<And>
A
<And>
B
C
</And>
</And>
Your SQL like sample translated to CAML (hopefully with matching XML tags ;) ):
<Where>
<And>
<Or>
<Eq>
<FieldRef Name='FirstName' />
<Value Type='Text'>John</Value>
</Eq>
<Or>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>John</Value>
</Eq>
<Eq>
<FieldRef Name='Profile' />
<Value Type='Text'>John</Value>
</Eq>
</Or>
</Or>
<And>
<Or>
<Eq>
<FieldRef Name='FirstName' />
<Value Type='Text'>Doe</Value>
</Eq>
<Or>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>Doe</Value>
</Eq>
<Eq>
<FieldRef Name='Profile' />
<Value Type='Text'>Doe</Value>
</Eq>
</Or>
If this helped you resolve your issue, please mark it Answered -
Is there a way to consolidate calculations used in SQL Query Data Sets?
I am building SQL Query Data Sets against multiple DB Views which all have different date formats. I have the date parameter working well, but want to consolidate the changes that I have to do to it especially for the quarter. For example the SQL against a monthly view would use "where year_month > to_char(:ST_DATE, 'YYYY-MM')" which is not too hard, but to make that work for the quarterly view I need several concats and a decode to get a "> '2012-Q2'". I would like not to have to do this within every where clause. I had put this into a global element hoping to use that in a filter for the data set, but the filter does not have access to global elements only parameters.
Is there any way to refer to a calculated global element from the data set to do this? I am using Layout Templates, so even if I wanted to I could not do the condition within the template.
Thanks,
RickChange the following line to include the red coloured parts
<div class="MasterColumn" spry:repeat="ds4" spry:setrow="ds4" spry:hover="MasterColumnHover" spry:select="MasterColumnSelected">
<span>{Dsp_#}</span><span>{Dsp_WkDay}</span><span>{Dsp_Event}</span>
</div>
The add the following style rule to your document:
.MasterColumn span {
display: inline-block;
I hope this helps.
Ben -
SQL Concat function seem not to work properly in SQL query data model. BIP 11g
I try to use this function to show entire name CONCAT(name, ' ', surname) and it doesnt show the surname. it looks like it only tooks 2 arguments. I use it with the option "Add element by expression" within a SQL Query - Data set.
Luciai don't believe you
please post more info, may be screen or sql or some more useful statement
CONCAT(name, ' ', surname) and it doesnt show the surname
may be because for some case "surname" is empty or may be you incorrect use concat function
one way mentioned by BluShadow is " || " operator - http://docs.oracle.com/cd/B28359_01/server.111/b28286/operators003.htm#SQLRF51156
and another is concat function http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions026.htm#SQLRF00619
so for your case it can be like
CONCAT(CONCAT(name, ' '), surname) -
Can I put a SQL query into a bind variable and then use it to output report
Hi,
Can I put a SQL query into a bind variable and then use it to output report?
I want to create a report and an item "text area" (say P1_TEXT) which can let user to input a SQL query(they are all technical users and knows SQL very well). Then, I use a bind variable (that text area) to store the SQL statement. Then, I add a submit button and I want to use the following to output the report:
select * from (:P1_TEXT);
Do you think it is possible to do that? Any known limitations for APEX in this area?
Thanks a lot,
AngelaYou can, but make sure it's what you really want to do. Make sure you are VERY familiar with SQL Injection. Most people who know what it is, go out of their way to prevent SQL Injection. You're going out of your way to allow it.
You can try using &P1_TEXT. instead of bind variable syntax. Bind variables are one of the best ways to prevent SQL Injection, which is why it's not working for you.
Once again, I strongly urge you to consider the implications of your app, but this suggestion should get it working.
Tyler -
SQL Query updateable report with row selector. Update process.
I have a SQL Query updateable report with the row selector(s).
How would I identify the row selector in an update process on the page.
I would like to update certain columns to a value of a select box on the page.
Using the basic:
UPDATE table_name
SET column1=value
WHERE some_column=some_value
I would need to do:
UPDATE table_name
SET column1= :P1_select
WHERE [row selector] = ?
Now sure how to identify the [row selector] and/or validate it is checked.
Thanks,
BobI don't have the apex_application.g_f01(i) referenced in the page source...In the page source you wouldn't find anything by that name
Identify the tabular form's checkbox column in the page(firebug/chrome developer panel makes this easy)
It should be like
<input id="..." value="" type="checkbox" name="fXX" >we are interested in the name attribute , get that number (between 01 and 50)
Replace that number in the code, for instance if it was f05 , the code would use
apex_application.g_f05
--i'th checked record' primary keyWhen you loop through a checkbox array, it only contains the rows which are checked and it is common practice to returns the record's primary key as the value of the checkbox(available as the the i'th array index as apex_application.g_f05(i) , where i is sequence position of the checked row) so that you can identify the record. -
Can someone please help, I have a dvd disk containing lecture videos, on a Windows pc it works fine, and the disk opens to the dvd menu. However on my macbook pro running Mountain Lion, it opens as a data disk, with video and audio in two seprate files??
You may need a 3rd party application to view the DVD in a wWindows format such as
http://flip4mac-3.en.softonic.com/mac
https://www.macupdate.com/app/iphone/5758/vlc-media-player -
Master Data Loading for Prices and Conditions in CRM - "/SAPCND/GCM"
Hi,
Could anyone give me some inputs on Master Data Loading for Prices and Conditions in CRM.
T. Code is: /SAPCND/GCM
I need to load data on a file (extracted from 4.6) for service contracts.
I tried LSMW : for this transaction, recording does not work.
I am trying loading thru Idocs (LSMW). But that too is note really working.
Do we require some custom development for this , or is some SAP standard funcntionality available ??
Can anyone provide some valuable inputs one this.
Would appreciate your responses.Hi Tiest,
Thanx for responding.
U r right, our clint is upgrading from 4.6 to ECC.
So as per the clients requirements, we are maintaining all the configs for Services in CRM.
Services Data which was in 4.6 is being pulled put on flat files which needs to be loaded in CRM. So middleware would not be able to do this.
What I am looking os some standard upload program.
LSMW recording does not work.
This I-Doc "CRMXIF_COND_REC_SLIM_SAVE_M", i am able to load a single record. But I am not able to find , how to make this function for multiple entries.
IN standard we for loading master data thru I-docs, we map the values to the standard fields which are available in that I-Doc.
But in this particular i-doc, there is a common field for which I need to define the field name and a field value..
Till now, I am only able to define just one field name and a field value.
I want this to word for mutliple entries.
Hope u get my point.
Thanx -
How to get sql query data and write into csv file?
I am writing to seek help, in how can I create bat. script which can execute the following logic:
connection to the database
run sql query
create CSV file
output query data, into CSV file
save the CSV file
osql
-S 84.18.111.111
-U adw
-P rem
-i "c:\query.sql"
send ""
sed -e 's/,\s\+/,/g' MCI_04Dec2014.csv > localNoSpaces.csv
-o "c:\MCI_04Dec2014.csv"
This what i have so far, and I am little struggling with the logic after creating CSV file. I am unable to get the above script to work, please advice further, where I may be going wrong.
Can you create if statement logic within window's script, to check for null parameters or data feeds?
Any hints would be most appreciated.Thank you for your reply.
Apology for posting the code irrelevant to the forum, as I am still novice scripting user.
My goal is to create window's script which can compute the above logic and send the final output file (csv), to FTP folder.
Can this logic be implemented via bat. script, if so, is there a example or tutorial i could follow, in order to achieve my task.
Any help would be much appreciated. -
Does SQL Query run faster with/without Conditions....
Hi All, forgive my novice question.
Was just wondering" In general if we run a SQL query on a single table; does my query run faster if there are multiple where conditions? or without. What happens if the conditions increase? My table is a big one with 5 million rows and some bitmap indexes defined on it.
Thanks,
KonI think it's difficult to give general rule because there are too much dependencies on the fact that the columns are indexed or not, on the way tables and indexes statistics are computed or not, on the possible session or instance parameters that the optimizer may use, on the Oracle version, etc.
Message was edited by:
Pierre Forstmann -
Need help with sql query dates
Hi,
I have a sql query where i need to extract some info between given dates. The where clause of this query is as follows:
WHERE CPD_BUS_UNIT=:ESI_PRM_1
AND CPD_VOUCHER_DATE >= :P_DATE_FROM
AND CPD_VOUCHER_DATE < (:P_DATE_TO+1)
When i execute the query in toad, i can view the data but not the execution plan.It gives an error ORA-00932-Inconsistent Datatypes.
But when i remove (+1) from :P_DATE_TO, i can c the execution plan and data. Will the data be different from the previous one.
Please suggest how to rewrite the query.Can you please give it a try?
WHERE CPD_BUS_UNIT=:ESI_PRM_1
AND CPD_VOUCHER_DATE >= :to_date(P_DATE_FROM)
AND CPD_VOUCHER_DATE < (to_date(:P_DATE_TO)+1) Regards -
SQL Query for full paid invoices and payed out credit notes
Hi alltogether,
I have some problems with a sql query.
I want to export all closed (full paid) invoices and credit notes in a table with the paid date.
The problem is that I have several internal reconciliations for one invoice or credit note.
So with my current query I get all these dates in the result but only for invoices, not for credit notes.
I only need the last internal reconciliation date as payment date for all invoices and credit notes where the open amount is 0.
In SAP B1 the finance team has service invoices and credit notes imported out of an ERP system.
These documents are marked with an 'Y" in the coloumn "U_I_Imported" in the table "OINV" or "ORIN".
SELECT
OINV.DocTotal - OINV.PaidToDate as Offen, OINV.NumAtCard, OINV.U_I_Imported, ORCT.DocDate as 'Zahlungsdatum'
SELECT
OINV.DocTotal - OINV.PaidToDate as Offen, OINV.NumAtCard, OINV.U_I_Imported, ORCT.DocDate as 'Zahlungsdatum'
FROM
OJDT inner join
ORCT on OJDT.BaseRef = ORCT.DocNum inner join
RCT2 on ORCT.DocNum = RCT2.DocNum inner join
OINV on RCT2.BaseAbs = OINV.DocEntry
where
OINV.DocTotal - OINV.PaidToDate = 0 and OINV.U_I_Imported = 'Y'
group by
OINV.NumatCard, OINV.DocTotal - OINV.PaidToDate, OINV.U_I_Imported, ORCT.DocDate
order by
ORCT.DocDate
I hope you can help me.
Kind regards,
MaxThe solution for my problem:
select
OINV.DocTotal - OINV.PaidToDate as 'Offen', OINV.CardCode as 'Kundennummer', OINV.NumAtCard as 'DIAMOD Rechnungsnummer', OINV.DocNum as 'Dokumentennummer', max(ORCT.DocDate) as 'Zahlungsdatum', case when ORCT.DocCurr = (select MainCurncy from OADM) then RCT2.DcntSum else RCT2.DcntSumFC end as 'SkontoRechnungswährung',
RCT2.DcntSum as 'SkontoFirmenwährung'
from
JDT1 inner join
OJDT on JDT1.TransId = OJDT.TransId inner join
ORCT on OJDT.BaseRef = ORCT.DocNum inner join
RCT2 on ORCT.DocNum = RCT2.DocNum inner join
OINV on RCT2.BaseAbs = OINV.DocEntry
where
JDT1.TransType in ('24') and
OINV.U_I_Imported = 'Y' and
OINV.DocTotal - OINV.PaidToDate = 0
group by
OINV.NumAtCard, OINV.DocNum, OINV.CardCode, OINV.DocTotal - OINV.PaidToDate, ORCT.DocCurr, RCT2.DcntSum, RCT2.DcntSumFC
union all
select
OINV.DocTotal - OINV.PaidToDate as Offen, OINV.CardCode as 'Kundennummer', OINV.NumAtCard as 'DIAMOD Rechnungsnummer', OINV.DocNum as 'Dokumentennummer', max(OITR.ReconDate) as 'Zahlungsdatum',
0.0 as 'SkontoRechnungswährung',
0.0 as 'SkontoFirmenwährung'
from
OITR inner join
ITR1 on OITR.ReconNum = ITR1.ReconNum inner join
OINV on ITR1.SrcObjAbs = OINV.DocEntry
where
OINV.DocTotal - OINV.PaidToDate = 0 and ITR1.SrcObjTyp = 13 and OINV.U_I_Imported = 'Y'
group by
OINV.NumatCard, OINV.DocNum, OINV.CardCode, OINV.DocTotal - OINV.PaidToDate
union all
select
ORIN.DocTotal - ORIN.PaidToDate as Offen, ORIN.CardCode as 'Kundennummer', ORIN.NumAtCard as 'DIAMOD Rechnungsnummer', ORIN.DocNum as 'Dokumentennummer', max(OITR.ReconDate) as 'Zahlungsdatum',
0.0 as 'SkontoRechnungswährung',
0.0 as 'SkontoFirmenwährung'
from
OITR inner join
ITR1 on OITR.ReconNum = ITR1.ReconNum inner join
ORIN on ITR1.SrcObjAbs = ORIN.DocEntry
where
ORIN.DocTotal - ORIN.PaidToDate = 0 and ITR1.SrcObjTyp = 14 and ORIN.U_I_Imported = 'Y'
group by
ORIN.NumatCard, ORIN.DocNum, ORIN.CardCode, ORIN.DocTotal - ORIN.PaidToDate
Maybe you are looking for
-
My ipod still works as far as powering up and operating is concerned, but it suddenly stopped outputting a signal through the sound jack. Also it no longer is detected by itunes in the source list.
-
Hi @ll, can anybody say why I get the syntax error The column name "VKORG" has two meanings. ABAP/4 Open SQL statement. Thanks Kam SELECT vtweg vmsta mtpos vkorg FROM MVKE INNER JOIN YMMARKET_CODE ON mvkevkorg = ymmarket_codevkorg I
-
Hello! I have a pearl 9105. OS 6.0 Bundle 2950 (6.6.0.236). I have a problem with screen rotation. When I go to browser, the screen won´t rotate. In the options I don´t find any options for rotate the screen. Is there any way to rotate the screen fo
-
10.5 beautiful OS, but still disappointingly unstable
Just had my first OS freeze under 10.5.4. Right-clicking a (Fireworks) .PNG file in the Finder to open it in FireForks made the Finder keel over and display its too-well-known Wheel Of Death. Every other open app on the system followed - one can swit
-
First Blackberry--- 4 questions to start!
I liked the storm a lot but I wasn't keen on the typing. Typing on the curve is tight, though, because the keys are so small and close. It was a close call. I've been playing with my pda all day.....loving it so far and assume I made the right cho