A query in AdventureWorks2012

Hi,
i have faced with a problem when i was working on a query in AddentureWorks2012 db
the query is as a follow :
show the name of product next to its sum(OrderQty) in each years
LIKE:      Year          |      Name   | Quantity
              2005                 x1            90
              2005                 x2            120
             2006                 x1             
100
             2006                 x2              
40
that would be your kindness, if you answer my question; Thanks

Sounds like this to me
SELECT Name,[1],[2],[3],[4],[5],..
FROM (
SELECT ROW_NUMBER OVER (PARTITION BY Name ORDER BY Year) AS Seq,Name,Year,Quantity
FROM Table
)t
PIVOT (SUM(Quantity) FOR Seq IN ([1],[2],[3],[4],..))p
If you want to make it dynamic based on available years 
see
http://sqlblogcasts.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx
Please Mark This As Answer if it solved your issue
Please Mark This As Helpful if it helps to solve your issue
Visakh
My MSDN Page
My Personal Blog
My Facebook Page

Similar Messages

  • Failing to import data using SQL query

    I am trying to import data from a sql query to analysis service in SSDT. i went to model > import from data source >Microsoft SQL Server and i chose from query. I typed my query which works fin in SSMS and when i press import if gives me a error. what
    is going on please help here is the error
    DirectQuery error: All tables used when querying in DirectQuery Mode must be from a single relational Data Source.
    here is my query:
    USE AdventureWorks2012;
    SELECT SalesPersonID, [29484] Brian, [29485] Peter, [29486] Frank, [29518] Sarah, [29519] Janet, [29520] Alice, [29608] Martin, [29609] Patrick, [29610] Wasu, [29780] Samanyika, [29781] Vladmire
    FROM
    SELECT SalesOrderID, SalesPersonID, CustomerID 
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
    As P PIVOT
    COUNT (SalesOrderID) FOR CustomerID IN ([29484], [29485], [29486], [29518],  [29519], [29520], [29608], [29609], [29610], [29780], [29781])
    AS PVT
    ORDER BY SalesPersonID ASC;

    Hi,
    When importing data from relational data source, the steps are:
    In SQL Server Data Tools (SSDT), click the Model menu, and then click Import
    from Data Source.
    On the Connect to a Data Source page, select the type of database to connect to, and then click Next.
    Follow the steps in the Table Import Wizard. On subsequent pages, you will be able to select specific tables and views or apply filters by using the Select
    Tables and Views page or by creating a SQL query on Specify a SQL Query page.
    As we can see on the steps, we need to select one database, so we needn't to write "USE AdventureWorks2012" on the query.
    Reference:Import from a Relational Data Source
    Regards,
    Charlie Liao
    TechNet Community Support

  • Show 2 different tables in same matrix

    I am using a Matrix report format in SSRS report builder, I only have one dataset to pull Invoice Date and Applied Date to show November, December (Monthly) amounts as column format and by Region (such as Americas, APAC, EMEA, Japan, Korea).
    However, the Matrix format cannot be displayed as below format (Month as the column, Region as the row).  In addition, I need to pull Quarterly field (as column) in the same grid (matrix format).
    Regarding the Applied Date I used in this dataset, I do have a condiction in SQL script since I need to compare with today's day. (Applied Date < Get(Date))
    How I can do that?  Appreciate if you can help me.
    Thanks,
    Josey
    Josey Tang

    <?xml version="1.0" encoding="utf-8"?>
    <Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
    <Body>
    <ReportItems>
    <Tablix Name="Tablix2">
    <TablixCorner>
    <TablixCornerRows>
    <TablixCornerRow>
    <TablixCornerCell>
    <CellContents>
    <Textbox Name="Textbox25">
    <CanGrow>true</CanGrow>
    <KeepTogether>true</KeepTogether>
    <Paragraphs>
    <Paragraph>
    <TextRuns>
    <TextRun>
    <Value />
    <Style>
    <FontFamily>Calibri</FontFamily>
    </Style>
    </TextRun>
    </TextRuns>
    <Style />
    </Paragraph>
    </Paragraphs>
    <rd:DefaultName>Textbox25</rd:DefaultName>
    <Style>
    <Border>
    <Color>LightGrey</Color>
    <Style>Solid</Style>
    </Border>
    <PaddingLeft>2pt</PaddingLeft>
    <PaddingRight>2pt</PaddingRight>
    <PaddingTop>2pt</PaddingTop>
    <PaddingBottom>2pt</PaddingBottom>
    </Style>
    </Textbox>
    </CellContents>
    </TablixCornerCell>
    </TablixCornerRow>
    <TablixCornerRow>
    <TablixCornerCell>
    <CellContents>
    <Textbox Name="Textbox23">
    <CanGrow>true</CanGrow>
    <KeepTogether>true</KeepTogether>
    <Paragraphs>
    <Paragraph>
    <TextRuns>
    <TextRun>
    <Value />
    <Style>
    <FontFamily>Calibri</FontFamily>
    </Style>
    </TextRun>
    </TextRuns>
    <Style />
    </Paragraph>
    </Paragraphs>
    <rd:DefaultName>Textbox23</rd:DefaultName>
    <Style>
    <Border>
    <Color>LightGrey</Color>
    <Style>Solid</Style>
    </Border>
    <PaddingLeft>2pt</PaddingLeft>
    <PaddingRight>2pt</PaddingRight>
    <PaddingTop>2pt</PaddingTop>
    <PaddingBottom>2pt</PaddingBottom>
    </Style>
    </Textbox>
    </CellContents>
    </TablixCornerCell>
    </TablixCornerRow>
    <TablixCornerRow>
    <TablixCornerCell>
    <CellContents>
    <Textbox Name="Textbox8">
    <CanGrow>true</CanGrow>
    <KeepTogether>true</KeepTogether>
    <Paragraphs>
    <Paragraph>
    <TextRuns>
    <TextRun>
    <Value>Name</Value>
    <Style>
    <FontFamily>Calibri</FontFamily>
    </Style>
    </TextRun>
    </TextRuns>
    <Style />
    </Paragraph>
    </Paragraphs>
    <rd:DefaultName>Textbox8</rd:DefaultName>
    <Style>
    <Border>
    <Color>LightGrey</Color>
    <Style>Solid</Style>
    </Border>
    <PaddingLeft>2pt</PaddingLeft>
    <PaddingRight>2pt</PaddingRight>
    <PaddingTop>2pt</PaddingTop>
    <PaddingBottom>2pt</PaddingBottom>
    </Style>
    </Textbox>
    </CellContents>
    </TablixCornerCell>
    </TablixCornerRow>
    </TablixCornerRows>
    </TablixCorner>
    <TablixBody>
    <TablixColumns>
    <TablixColumn>
    <Width>1in</Width>
    </TablixColumn>
    </TablixColumns>
    <TablixRows>
    <TablixRow>
    <Height>0.25in</Height>
    <TablixCells>
    <TablixCell>
    <CellContents>
    <Textbox Name="Amount">
    <CanGrow>true</CanGrow>
    <KeepTogether>true</KeepTogether>
    <Paragraphs>
    <Paragraph>
    <TextRuns>
    <TextRun>
    <Value>=Sum(Fields!Amount.Value)</Value>
    <Style>
    <FontFamily>Calibri</FontFamily>
    <Format>c</Format>
    </Style>
    </TextRun>
    </TextRuns>
    <Style />
    </Paragraph>
    </Paragraphs>
    <rd:DefaultName>Amount</rd:DefaultName>
    <Style>
    <Border>
    <Color>LightGrey</Color>
    <Style>Solid</Style>
    </Border>
    <PaddingLeft>2pt</PaddingLeft>
    <PaddingRight>2pt</PaddingRight>
    <PaddingTop>2pt</PaddingTop>
    <PaddingBottom>2pt</PaddingBottom>
    </Style>
    </Textbox>
    </CellContents>
    </TablixCell>
    </TablixCells>
    </TablixRow>
    </TablixRows>
    </TablixBody>
    <TablixColumnHierarchy>
    <TablixMembers>
    <TablixMember>
    <Group Name="Quarter">
    <GroupExpressions>
    <GroupExpression>=Fields!Quarter.Value</GroupExpression>
    </GroupExpressions>
    </Group>
    <SortExpressions>
    <SortExpression>
    <Value>=Fields!Quarter.Value</Value>
    </SortExpression>
    </SortExpressions>
    <TablixHeader>
    <Size>0.25in</Size>
    <CellContents>
    <Textbox Name="Quarter">
    <CanGrow>true</CanGrow>
    <KeepTogether>true</KeepTogether>
    <Paragraphs>
    <Paragraph>
    <TextRuns>
    <TextRun>
    <Value>="Quarter " &amp; Fields!Quarter.Value</Value>
    <Style>
    <FontFamily>Calibri</FontFamily>
    </Style>
    </TextRun>
    </TextRuns>
    <Style>
    <TextAlign>Center</TextAlign>
    </Style>
    </Paragraph>
    </Paragraphs>
    <rd:DefaultName>Quarter</rd:DefaultName>
    <Style>
    <Border>
    <Color>LightGrey</Color>
    <Style>Solid</Style>
    </Border>
    <PaddingLeft>2pt</PaddingLeft>
    <PaddingRight>2pt</PaddingRight>
    <PaddingTop>2pt</PaddingTop>
    <PaddingBottom>2pt</PaddingBottom>
    </Style>
    </Textbox>
    </CellContents>
    </TablixHeader>
    <TablixMembers>
    <TablixMember>
    <Group Name="Month">
    <GroupExpressions>
    <GroupExpression>=Fields!Month.Value</GroupExpression>
    </GroupExpressions>
    </Group>
    <SortExpressions>
    <SortExpression>
    <Value>=Fields!Month.Value</Value>
    </SortExpression>
    </SortExpressions>
    <TablixHeader>
    <Size>0.25in</Size>
    <CellContents>
    <Textbox Name="Month">
    <CanGrow>true</CanGrow>
    <KeepTogether>true</KeepTogether>
    <Paragraphs>
    <Paragraph>
    <TextRuns>
    <TextRun>
    <Value>=MonthName(Fields!Month.Value)</Value>
    <Style>
    <FontFamily>Calibri</FontFamily>
    </Style>
    </TextRun>
    </TextRuns>
    <Style>
    <TextAlign>Center</TextAlign>
    </Style>
    </Paragraph>
    </Paragraphs>
    <rd:DefaultName>Month</rd:DefaultName>
    <Style>
    <Border>
    <Color>LightGrey</Color>
    <Style>Solid</Style>
    </Border>
    <PaddingLeft>2pt</PaddingLeft>
    <PaddingRight>2pt</PaddingRight>
    <PaddingTop>2pt</PaddingTop>
    <PaddingBottom>2pt</PaddingBottom>
    </Style>
    </Textbox>
    </CellContents>
    </TablixHeader>
    <TablixMembers>
    <TablixMember>
    <Group Name="GroupType">
    <GroupExpressions>
    <GroupExpression>=Fields!GroupType.Value</GroupExpression>
    </GroupExpressions>
    </Group>
    <SortExpressions>
    <SortExpression>
    <Value>=Fields!Month.Value</Value>
    </SortExpression>
    </SortExpressions>
    <TablixHeader>
    <Size>0.25in</Size>
    <CellContents>
    <Textbox Name="GroupType">
    <CanGrow>true</CanGrow>
    <KeepTogether>true</KeepTogether>
    <Paragraphs>
    <Paragraph>
    <TextRuns>
    <TextRun>
    <Value>=Fields!GroupType.Value</Value>
    <Style>
    <FontFamily>Calibri</FontFamily>
    </Style>
    </TextRun>
    </TextRuns>
    <Style>
    <TextAlign>Center</TextAlign>
    </Style>
    </Paragraph>
    </Paragraphs>
    <rd:DefaultName>GroupType</rd:DefaultName>
    <Style>
    <Border>
    <Color>LightGrey</Color>
    <Style>Solid</Style>
    </Border>
    <PaddingLeft>2pt</PaddingLeft>
    <PaddingRight>2pt</PaddingRight>
    <PaddingTop>2pt</PaddingTop>
    <PaddingBottom>2pt</PaddingBottom>
    </Style>
    </Textbox>
    </CellContents>
    </TablixHeader>
    </TablixMember>
    </TablixMembers>
    </TablixMember>
    </TablixMembers>
    </TablixMember>
    </TablixMembers>
    </TablixColumnHierarchy>
    <TablixRowHierarchy>
    <TablixMembers>
    <TablixMember>
    <Group Name="Name">
    <GroupExpressions>
    <GroupExpression>=Fields!Name.Value</GroupExpression>
    </GroupExpressions>
    </Group>
    <SortExpressions>
    <SortExpression>
    <Value>=Fields!Name.Value</Value>
    </SortExpression>
    </SortExpressions>
    <TablixHeader>
    <Size>1.16667in</Size>
    <CellContents>
    <Textbox Name="Name">
    <CanGrow>true</CanGrow>
    <KeepTogether>true</KeepTogether>
    <Paragraphs>
    <Paragraph>
    <TextRuns>
    <TextRun>
    <Value>=Fields!Name.Value</Value>
    <Style>
    <FontFamily>Calibri</FontFamily>
    </Style>
    </TextRun>
    </TextRuns>
    <Style />
    </Paragraph>
    </Paragraphs>
    <rd:DefaultName>Name</rd:DefaultName>
    <Style>
    <Border>
    <Color>LightGrey</Color>
    <Style>Solid</Style>
    </Border>
    <PaddingLeft>2pt</PaddingLeft>
    <PaddingRight>2pt</PaddingRight>
    <PaddingTop>2pt</PaddingTop>
    <PaddingBottom>2pt</PaddingBottom>
    </Style>
    </Textbox>
    </CellContents>
    </TablixHeader>
    </TablixMember>
    </TablixMembers>
    </TablixRowHierarchy>
    <DataSetName>DataSet1</DataSetName>
    <Top>0.49875in</Top>
    <Left>0.4675in</Left>
    <Height>1in</Height>
    <Width>2.16667in</Width>
    <Style>
    <Border>
    <Style>None</Style>
    </Border>
    </Style>
    </Tablix>
    </ReportItems>
    <Height>2in</Height>
    <Style />
    </Body>
    <Width>6.5in</Width>
    <Page>
    <LeftMargin>1in</LeftMargin>
    <RightMargin>1in</RightMargin>
    <TopMargin>1in</TopMargin>
    <BottomMargin>1in</BottomMargin>
    <Style />
    </Page>
    <AutoRefresh>0</AutoRefresh>
    <DataSources>
    <DataSource Name="AdventureWorks2012">
    <DataSourceReference>AdventureWorks2012</DataSourceReference>
    <rd:SecurityType>None</rd:SecurityType>
    <rd:DataSourceID>484e6561-ee09-4a7e-ad66-82f98face825</rd:DataSourceID>
    </DataSource>
    </DataSources>
    <DataSets>
    <DataSet Name="DataSet1">
    <Query>
    <DataSourceName>AdventureWorks2012</DataSourceName>
    <CommandText>SELECT
    'Invoice' AS GroupType,
    DATEPART(qq, soh.OrderDate) AS [Quarter],
    MONTH(soh.OrderDate) AS [Month],
    st.Name,
    SUM(soh.TotalDue) AS Amount
    FROM
    Sales.SalesOrderHeader AS soh
    JOIN Sales.SalesTerritory AS st
    ON soh.TerritoryID = st.TerritoryID
    WHERE
    year(soh.OrderDate) = 2008
    GROUP BY
    DATEPART(qq, soh.OrderDate),
    MONTH(soh.OrderDate),
    st.Name
    UNION ALL
    SELECT
    'Applied' AS GroupType,
    DATEPART(qq, soh.ShipDate) AS [Quarter],
    MONTH(soh.ShipDate) AS [Month],
    st.Name,
    SUM(soh.SubTotal) AS Amount
    FROM
    Sales.SalesOrderHeader AS soh
    JOIN Sales.SalesTerritory AS st
    ON soh.TerritoryID = st.TerritoryID
    WHERE
    year(soh.ShipDate) = 2008
    GROUP BY
    DATEPART(qq, soh.ShipDate),
    MONTH(soh.ShipDate),
    st.Name</CommandText>
    </Query>
    <Fields>
    <Field Name="GroupType">
    <DataField>GroupType</DataField>
    <rd:TypeName>System.String</rd:TypeName>
    </Field>
    <Field Name="Quarter">
    <DataField>Quarter</DataField>
    <rd:TypeName>System.Int32</rd:TypeName>
    </Field>
    <Field Name="Month">
    <DataField>Month</DataField>
    <rd:TypeName>System.Int32</rd:TypeName>
    </Field>
    <Field Name="Name">
    <DataField>Name</DataField>
    <rd:TypeName>System.String</rd:TypeName>
    </Field>
    <Field Name="Amount">
    <DataField>Amount</DataField>
    <rd:TypeName>System.Decimal</rd:TypeName>
    </Field>
    </Fields>
    </DataSet>
    </DataSets>
    <rd:ReportUnitType>Inch</rd:ReportUnitType>
    <rd:ReportID>3523f80e-1b49-43df-a36c-d80292f6a41a</rd:ReportID>
    </Report>
    Jason Long

  • Where did the securables go? Created Databse Role add Securables and Permission but it disappeared.

    Hello my friends:
    Create a Database Role, added Securables and set the Permissions. These are all stored Procedures.
    When I clicked Okay I get a message that the role was created successfully.
    Now I go back to the database role, click properties and the securables are not showing?
    Is this normal behavior? Where did they go?
    Thanks!

    I have sufficient rights: The DB Role is working because Users who I have assigned the Role Are able to do what they need. I just cannot see the securables when I go to properties. I also have a SYS Admin account, I log in as SYS Admin and still cannot see
    the securables.
    However, if I click on an individual user who is assigned to the role, I can see the securables from the properties tab.
    Hi,
    First check that you can see the role using a query:
    USE AdventureWorks2012;
    GO
    CREATE ROLE ArielyRole322
    GO
    Select * from sys.database_principals where name = 'ArielyRole322' and type = 'R'
    GO
    and now you can use the GUI interface as well:
    open the database -> security -> Roles -> Database Roles -> and here it is :-)
      Ronen Ariely
     [Personal Site]    [Blog]    [Facebook]

  • Outputing Total Numbers of Rows Returned in query using a CTE

    The query below is not being parsed by SQL Server and I can understand that the column name needs to be aliased which I have equally done. The idea behind the query is to output the count of rows using a CTE.
    USE AdventureWorks2012
    DECLARE @TotalRows INT = 0 -- OUTPUT
    WITH Invoice AS (
    SELECT @TotalRows = COUNT(CustomerID)
    , SalesOrderID
    , CustomerID
    , OrderDate
    FROM Sales.SalesOrderHeader
    WHERE OrderDate = '2007/07/01'
    GROUP BY SalesOrderID
    , CustomerID
    , OrderDate
    SELECT c.CustomerID
    , Invoice.SalesOrderID
    , Invoice.OrderDate
    FROM Sales.Customer AS c
    INNER JOIN Invoice
    ON c.CustomerID = Invoice.CustomerID
    ORDER BY Invoice.OrderDate DESC;
    How do I modify the query to produce the desired retult?
    Thank you.
    Zionlite

    Zionlite,
    check this>?
    DECLARE @TotalRows INT = 0 -- OUTPUT
    ;WITH Invoice AS
    SELECT COUNT(CustomerID) over()
    as customer_count
    , SalesOrderID
    , CustomerID
    , OrderDate
    FROM Sales.SalesOrderHeader
    WHERE OrderDate = '2001/07/01'
    GROUP BY SalesOrderID
    , CustomerID
    , OrderDate
    SELECT c.CustomerID
    , Invoice.SalesOrderID
    , Invoice.OrderDate
    , customer_count
    FROM Invoice
    LEFT JOIN Sales.Customer AS c
    ON c.CustomerID = Invoice.CustomerID
    ORDER BY Invoice.OrderDate DESC;
    So the above query, gives you the rows_count as a seprate column itself. Now you may use this to update the variable by pushing the results to  a temp table and selecting the column value.
    Method 2:
    Another method can be using the rowcount method..
    DECLARE @TotalRows INT = 0 -- OUTPUT
    ;WITH Invoice AS
    SELECT SalesOrderID
    , CustomerID
    , OrderDate
    FROM Sales.SalesOrderHeader
    WHERE OrderDate = '2001/07/01'
    GROUP BY SalesOrderID
    , CustomerID
    , OrderDate
    SELECT c.CustomerID
    , Invoice.SalesOrderID
    , Invoice.OrderDate
    FROM Invoice
    LEFT JOIN Sales.Customer AS c
    ON c.CustomerID = Invoice.CustomerID
    ORDER BY Invoice.OrderDate DESC;
    select @totalrows=@@rowcount
    select @TotalRows
    Thanks,
    Jay
    <If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>

  • Update users in Active Directory form SQL query update

    I need to update the fields in the
    Active Directory 2003 users from a
    SQL Server 2003 query. Any idea plissss???

    This is an powershell example to create AD users from SQL Server.
    The Powershell cmdlet Set-ADUser will update the AD User fields.
    $SQLText = "SELECT e.BusinessEntityID, p.Title, p.FirstName, p.MiddleName, p.LastName, p.Suffix, "+
    "e.JobTitle, d.Name AS Department, d.GroupName, edh.StartDate, e.LoginID"+
    " FROM HumanResources.Employee AS e"+
    " INNER JOIN Person.Person AS p ON p.BusinessEntityID = e.BusinessEntityID"+
    " INNER JOIN HumanResources.EmployeeDepartmentHistory AS edh ON e.BusinessEntityID = edh.BusinessEntityID"+
    " INNER JOIN HumanResources.Department AS d ON edh.DepartmentID = d.DepartmentID"+
    " WHERE (edh.EndDate IS NULL)"+
    " AND (p.FirstName ='Brian')"
    $SqlCon = New-Object System.Data.SqlClient.SqlConnection
    $SqlCon.ConnectionString = "Server=localhost;Database=AdventureWorks2012;Trusted_Connection=yes;;"
    $SqlCon.Open()
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.Connection = $SqlCon
    $SqlCmd = $SqlCon.CreateCommand()
    $SQLCmd.CommandText = $SQLText
    $Result = $SQLCmd.ExecuteReader()
    $Table = New-Object System.Data.DataTable
    $table.Load($Result)
    $SqlCon.Close()
    $Password = "P@assword1"
    foreach($Item in $Table)
    $newUserID=@{
    Name=$item.FirstName+$Item.LastName
    Description="This is a test of a bulk user add"
    GivenName=$item.FirstName
    Surname=$item.LastName
    DisplayName=$item.FirstName+" "+$Item.LastName
    UserPrincipalName="$($item.FirstName+"."+$Item.LastName)@corp.contoso.com"
    EmployeeID=$item.BusinessEntityID
    ScriptPath='login.cmd'
    Company="Contoso"
    Department=$Item.Department
    EmailAddress="$($item.FirstName+"."+$Item.LastName)@corp.contoso.com"
    Title=$Item.JobTitle
    $TargetOU="OU="+$item.Department+",DC=corp,DC=contoso,DC=com"
    Try{
    $newUserID
    New-ADUser @newUserID -Path $TargetOU -ErrorAction Stop -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Passthru
    Enable-ADAccount -Identity $newUserID.Name
    Set-ADUser -Identity $newUserID.Name -ChangePasswordAtLogon $true
    Write-Host "UserID $($newUserID.Name) created!" -ForegroundColor green
    Catch{
    Write-Host "There was a problem creating UserID $($item.UserID). The account was not created!" -ForegroundColor Red

  • Is this Join Query Syntax Correct???

    Is this syntax correct for this query question?  Would "used Vista cards" reflect the OrderDate Column in the where clause.  The table is from Adventureworks2012.
    How many Sales Orders (Headers) used Vista credit cards in October 2002 
    SELECT C.CardType, COUNT(*)
    FROM Sales.SalesOrderHeader S 
    JOIN Sales.CreditCard
      C
    ON S.CreditCardID=c.CreditCardID
    WHERE C.CardType = 'Vista'
    AND S.OrderDate  between '10/1/2002' and '10/31/2002'
    GROUP BY c.CardType
      

    That is correct, but be careful when writing queries where a datetime column is compared to a period of time.  In this case it looks like the time portions of OrderDate are all set to the beginning of day (00:00:00.000) so your query works as long as
    that assumption is correct.  The better way is to use an upper boundary of the next day (which means you cannot use between).  E.g., 
    select ... where S.OrderDate >= '20021001' and S.OrderDate < '20021101' 
    group by ...
    order by ...;
    If you search for the forum for "Tibor" you should be able to find a link to his website where he goes into much more detail about the tricky usage of the datetime datatype. 

  • To Get List of Tables from Database which has the data 'AAAA' - T-SQL Query

    Hi,
    I have a database "Adventureworks", I need to get list of tables, which has the data 'AAAA' in their rows.
    Is there any optimised or simple way to do this task?
    Any T-SQL Query Available
    --- Thanks in advance..

    You can refer the same below URL provided by Praveen:
    https://gallery.technet.microsoft.com/scriptcenter/c0c57332-8624-48c0-b4c3-5b31fe641c58
    It has the SQL SP - "SP_SearchTables". You can pass parameters the way you want and get the expected output.
    -- Search for 'bike' instead of 'AAAA'
    Use AdventureWorks2012
    EXEC SP_SearchTables @Tablenames = '%', @SearchStr = '%bike%'
    -Vaibhav Chaudhari

  • Error while running a query-Input for variable 'Posting Period is invalid

    Hi All,
    NOTE: This error is only cropping up when I input 12 in the posting period variable selection. If I put in any other value from 1-11 I am not getting any errors. Any ideas why this might be happening?
    I am getting the following error when I try and run a query - "Input for variable 'Posting Period (Single entry, mandatory)' is invalid" - On further clicking on this error the message displayed is as follows -
    Diagnosis
    Variable Posting Period (Single Value Entry, Mandatory) is used as a lower limit (X) and an upper limit () in an interval selection. This limit has the value #.
    System Response
    Procedure
    Enter a different value for variable Posting Period (Single Value Entry, Mandatory). If the value of the other limit is determined by another variable, you can change its value also.
    Procedure for System Administration

    OK.
    Well, if the variable is not used in any interval selection, then I would say "something happened to it".
    I would make a copy of the query and run it to check if I get the same problem with period 12.
       -> If not, something is wrong in the original query (you can proceed as below, if changes to original are permitted).
    If so, then try removing the variable completely from the query and hardcode restriction to 12.
       -> If problem still persists, I would have to do some thinking.
    If problem is gone, then add the variable again. Check.
       -> If problem is back, then the variable "is sick". Only quick thing to do, is to build an identical variable and use that one.
    If problem also happens with the new variable, then it's time to share this experience with someone else and consider raising an OSS.
    Good luck!
    Jacob
    P.S: what fisc year variant are you using?
    Edited by: Jacob Jansen on Jan 25, 2010 8:36 PM

  • Logical database in adhoc query

    Hello All,
    Can anyone tell me what is the logical database in adhoc query?

    Hi
    When you create a query , you have to select an infoset. Infoset can be considered as a source from which data is populated in the Query Fields.
    Infosets are created from Transaction SQ02.
    There can be four methods through which an Infoset can become a source of data:
    1.  Table join ( By joining two or more tables from Data dictionary)
         example: Joining tables PA0001 and PA0006 on Pernr to get a one resultant dataset
    2. Direct read of Basis Table ( Like PA0001 as a source for data in Infoset )
    3. Logical Database ( A Pre-written Program by SAP that extract data from clusters, tables taking care of authorizations and validity periods)
    Example : Logical database PNP, PNPCE (Concurrent Employement),PCH ( LDB for Personnel Development Data)
    Custom Logical DBs can be created in T_Code SE-36.
    4. Data Retrieval by a Program ( Custom code written by ABAP developers which will collect and process data) . This program has a corresponding Structure in data dictionary and the fields of this structure will be used in query)
    Reward Points, if helpful.
    Regards
    Waseem Imran

  • Query help on Goods Receipt Query with AP Invoice

    Looking for a little help on a query.  I would like to list all the goods receipts for a given date range and then display the AP Invoice information (if its been copied to an AP Invoice).  I think my problem is in my where clause, I plagerized an SAP query to show GR and AP from a PO as a start.  SBO 2005 SP01.  Any help would be great appreciated.  Thanks
    SELECT distinct 'GR',
    D0.DocStatus,
    D0.DocNum ,
    D0.DocDate,
    D0.DocDueDate,
    D0.DocTotal,
    'AP',
    I0.DocStatus,
    I0.DocNum ,
    I0.DocDate,
    I0.DocDueDate,
    I0.DocTotal,
    I0.PaidToDate
    FROM
    ((OPDN  D0 inner Join PDN1 D1 on D0.DocEntry = D1.DocEntry)
    full outer join
    (OPCH I0 inner join PCH1 I1 on I0.DocEntry = I1.DocEntry)
    on (I1.BaseType=20 AND D1.DocEntry = I1.BaseEntry AND D1.LineNum=I1.BaseLine))
    WHERE
    (D1.BaseType=22 AND D1.DocDate>='[%0]' AND D1.DocDate<='[%1]')
    OR (I1.BaseType=20 AND I1.BaseEntry IN
    (SELECT Distinct DocEntry
    FROM PDN1 WHERE BaseType=22 AND DocDate>='[%0]' AND DocDate<='[%1]'))

    Hi Dalen ,
    I  believe it is because of the condition
    (D1.BaseType=22 AND D1.DocDate>='%0' AND D1.DocDate<='%1')
    OR (I1.BaseType=20 AND I1.BaseEntry IN
    (SELECT Distinct DocEntry FROM PDN1 WHERE PDN1.BaseType=22 AND DocDate>='%0' AND DocDate<='%1'))
    Try changing
    D1.BaseType=22 OR D1.DocDate>='%0' AND D1.DocDate<='%1
    PDN1.BaseType=22 OR DocDate>='%0' AND DocDate<='%1'))
    Lets see what would be the result . Lets have some fun with troubleshooting
    See what would be the difference in the result .
    Thank you
    Bishal

  • Can you check for data in one table or another but not both in one query?

    I have a situation where I need to link two tables together but the data may be in another (archive) table or different records are in both but I want the latest record from either table:
    ACCOUNT
    AccountID     Name   
    123               John Doe
    124               Jane Donaldson           
    125               Harold Douglas    
    MARKETER_ACCOUNT
    Key     AccountID     Marketer    StartDate     EndDate
    1001     123               10526          8/3/2008     9/27/2009
    1017     123               10987          9/28/2009     12/31/4712    (high date ~ which means currently with this marketer)
    1023     124               10541          12/03/2010     12/31/4712
    ARCHIVE
    Key     AccountID     Marketer    StartDate     EndDate
    1015     124               10526          8/3/2008     12/02/2010
    1033     125               10987         01/01/2011     01/31/2012  
    So my query needs to return the following:
    123     John Doe                        10526     8/3/2008     9/27/2009
    124     Jane Donaldson             10541     12/03/2010     12/31/4712     (this is the later of the two records for this account between archive and marketer_account tables)
    125     Harold Douglas               10987          01/01/2011     01/31/2012     (he is only in archive, so get this record)
    I'm unsure how to proceed in one query.  Note that I am reading in possibly multiple accounts at a time and returning a collection back to .net
    open CURSOR_ACCT
              select AccountID
              from
                     ACCOUNT A,
                     MARKETER_ACCOUNT M,
                     ARCHIVE R
               where A.AccountID = nvl((select max(M.EndDate) from Marketer_account M2
                                                    where M2.AccountID = A.AccountID),
                                                      (select max(R.EndDate) from Archive R2
                                                    where R2.AccountID = A.AccountID)
                   and upper(A.Name) like parameter || '%'
    <can you do a NVL like this?   probably not...   I want to be able to get the MAX record for that account off the MarketerACcount table OR the max record for that account off the Archive table, but not both>
    (parameter could be "DO", so I return all names starting with DO...)

    if I understand your description I would assume that for John Dow we would expect the second row from marketer_account  ("high date ~ which means currently with this marketer"). Here is a solution with analytic functions:
    drop table account;
    drop table marketer_account;
    drop table marketer_account_archive;
    create table account (
        id number
      , name varchar2(20)
    insert into account values (123, 'John Doe');
    insert into account values (124, 'Jane Donaldson');
    insert into account values (125, 'Harold Douglas');
    create table marketer_account (
        key number
      , AccountId number
      , MktKey number
      , FromDt date
      , ToDate date
    insert into marketer_account values (1001, 123, 10526, to_date('03.08.2008', 'dd.mm.yyyy'), to_date('27.09.2009', 'dd.mm.yyyy'));
    insert into marketer_account values (1017, 123, 10987, to_date('28.09.2009', 'dd.mm.yyyy'), to_date('31.12.4712', 'dd.mm.yyyy'));
    insert into marketer_account values (1023, 124, 10541, to_date('03.12.2010', 'dd.mm.yyyy'), to_date('31.12.4712', 'dd.mm.yyyy'));
    create table marketer_account_archive (
        key number
      , AccountId number
      , MktKey number
      , FromDt date
      , ToDate date
    insert into marketer_account_archive values (1015, 124, 10526, to_date('03.08.2008', 'dd.mm.yyyy'), to_date('02.12.2010', 'dd.mm.yyyy'));
    insert into marketer_account_archive values (1033, 125, 10987, to_date('01.01.2011', 'dd.mm.yyyy'), to_date('31.01.2012', 'dd.mm.yyyy'));
    select key, AccountId, MktKey, FromDt, ToDate
         , max(FromDt) over(partition by AccountId) max_FromDt
      from marketer_account
    union all
    select key, AccountId, MktKey, FromDt, ToDate
         , max(FromDt) over(partition by AccountId) max_FromDt
      from marketer_account_archive;
    with
    basedata as (
    select key, AccountId, MktKey, FromDt, ToDate
      from marketer_account
    union all
    select key, AccountId, MktKey, FromDt, ToDate
      from marketer_account_archive
    basedata_with_max_intervals as (
    select key, AccountId, MktKey, FromDt, ToDate
         , row_number() over(partition by AccountId order by FromDt desc) FromDt_Rank
      from basedata
    filtered_basedata as (
    select key, AccountId, MktKey, FromDt, ToDate from basedata_with_max_intervals where FromDt_Rank = 1
    select a.id
         , a.name
         , b.MktKey
         , b.FromDt
         , b.ToDate
      from account a
      join filtered_basedata b
        on (a.id = b.AccountId)
    ID NAME                     MKTKEY FROMDT     TODATE
    123 John Doe                  10987 28.09.2009 31.12.4712
    124 Jane Donaldson            10541 03.12.2010 31.12.4712
    125 Harold Douglas            10987 01.01.2011 31.01.2012
    If your tables are big it could be necessary to do the filtering (according to your condition) in an early step (the first CTE).
    Regards
    Martin

  • Query help : Query to get values SYSDATE-1 18:00 hrs to SYSDATE 08:00 hrs

    Hi Team
    I want the SQl query to get the data for the following comparison : -
    Order Created is a Date Column , and i want to find out all the values from (SYSDATE-1) 18:00 hours to SYSDATE 08:00 hours
    i.e.
    (SYSDATE-1) 18:00:00 < Order.Created < SYSDATE 08:00:00.
    Regards

    Hi, Rohit,
    942281 wrote:
    If i want the data in the below way i.e.
    from (SYSDATE-1) 18:00 hours to SYSDATE 17:59 hours ---> (SYSDATE-1) 18:00:00 < Order.Created < SYSDATE 07:59:00.If you want to include rows from exactly 18:00:00 yesterday (but no earlier), and exclude rows from exatly 08:00:00 today (or later), then use:
    WHERE   ord_dtl.submit_dt  >= TRUNC (SYSDATE) - (6 / 24)
    AND     ord_dtl.submit_dt  <  TRUNC (SYSDATE) + (8 / 24)
    So can i use the below format : -
    ord_dtl.submit_dt BETWEEN trunc(sysdate)-(6/24) and trunc(sysdate)+(7.59/24) . Please suggest . .59 hours is .59 * 60 * 60 = 2124 seconds (or .59 * 60 = 35.4 minutes), so the last time included in the range above is 07:35:24, not 07:59:59.
    If you really, really want to use BETWEEN (which includes both end points), then you could do it with date arithmentic:
    WHERE   ord_dtl.submit_dt  BETWEEN  TRUNC (SYSDATE) - (6 / 24)
                      AND         TRUNC (SYSDATE) + (8 / 24)
                                               - (1 / (24 * 60 * 60))but it would be simpler and less error prone to use INTERVALs, as Karthick suggested earlier:
    WHERE   ord_dtl.submit_dt  BETWEEN  TRUNC (SYSDATE) - INTERVAL '6' HOUR
                      AND         TRUNC (SYSDATE) + INTERVAL '8' HOUR
                                               - INTERVAL '1' SECONDEdited by: Frank Kulash on Apr 17, 2013 9:36 AM
    Edited by: Frank Kulash on Apr 17, 2013 11:56 AM
    Changed "- (8 /24)" to "+ (8 /24)" in first code fragment (after Blushadown, below)

  • Query help, subtract two query parts

    Hi,
    I am beginner of PL/SQL and have a problem I couldn’t solve:
    Table (op_list):
    Item     -     Amount -     Status
    Item1     -     10     -     in
    Item2     -     12     -     in
    Item3     -     7     -     in
    Item1     -     2     -     out
    Item2     -     3     -     out
    Item1     -     1     -     dmg
    Item3     -     3     -     out
    Item1     -     2     -     out
    Item2     -     5     -     out
    Item2     -     2     -     in
    Item3     -     1     -     exp
    Would like to get result of query (subtract amount of 'out/dmg/exp' from 'in' ):
    Item - Amount left
    Item1     -     5
    Item2     -     6
    Item3 -     3
    I wrote code that returns sum of all incoming items and sum all out/dmg/exp items, but couldn’t solve how to subtract one part of querry from another. Or maybe there is a better way. Also worried what happens if there is no 'out/dmg/exp' only 'in'
    select item.name, sum(op_list.item_amount)
    from op_list
    inner join item
    on op_list.item = item.item_id
    where op_list.status = 'in'
    group by item.name
    union
    select item.name, sum(op_list.item_amount)
    from op_list
    inner join item
    on op_list.item = item.item_id
    where op_list.status = 'out'
    or op_list.status = 'dmg'
    or op_list.status = 'exp'
    group by item.name
    Return:
    Item1     -     10      [10 in]
    Item1     -     5     [2+1+2]
    Item2     -     14     [12+2]
    Item3     -     7
    Item3     -     4     [3+1]
    Thanks in advance

    Hi,
    We can also use simple inline views to get what we need.
    select a.item,a.amount-b.amount Balance from
    (select item,sum(amount) Amount from op_list
    where status = 'in'
    group by item) a,
    (select item,sum(amount) Amount from op_list
    where status in ('out','dmg','exp')
    group by item) b
    where
    a.item=b.item
    order by item;
    ITEM       BALANCE
    Item1                      5
    Item2                      6
    Item3                      3Regards,
    Prazy

  • Query help: query to return column that represents multiple rows

    I have a table with a name and location column. The same name can occur multiple times with any arbitrary location, i.e. duplicates are allowed.
    I need a query to find all names that occur in both of two separate locations.
    For example,
    bob usa
    bob mexico
    dot mexico
    dot europe
    hal usa
    hal europe
    sal usa
    sal mexico
    The query in question, if given the locations usa and mexico, would return bob and sal.
    Thanks for any help or advice,
    -=beeky

    How about this?
    SELECT  NAME
    FROM    <LOCATIONS_TABLE>
    WHERE   LOCATION IN ('usa','mexico')
    GROUP BY NAME
    HAVING COUNT(DISTINCT LOCATION) >= 2Results:
    SQL> WITH person_locations AS
      2  (
      3          SELECT 'bob' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
      4          SELECT 'bob' AS NAME, 'Mexico' AS LOCATION FROM DUAL UNION ALL
      5          SELECT 'dot' AS NAME, 'Mexico' AS LOCATION FROM DUAL UNION ALL
      6          SELECT 'dot' AS NAME, 'Europe' AS LOCATION FROM DUAL UNION ALL
      7          SELECT 'hal' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
      8          SELECT 'hal' AS NAME, 'Europe' AS LOCATION FROM DUAL UNION ALL
      9          SELECT 'sal' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
    10          SELECT 'sal' AS NAME, 'Mexico' AS LOCATION FROM DUAL
    11  )
    12  SELECT  NAME
    13  FROM    person_locations
    14  WHERE   LOCATION IN ('USA','Mexico')
    15  GROUP BY NAME
    16  HAVING COUNT(DISTINCT LOCATION) >= 2
    17  /
    NAM
    bob
    salHTH!
    Edited by: Centinul on Oct 15, 2009 2:25 PM
    Added sample results.

Maybe you are looking for

  • A Motherboard that doesn't POWER UP?? Please Help Me :(

    Ok! Hi, this is my first post, but I ain't an MSI new customer. I've built about 5 computers using MSI products, including my own... Let's get to the topic since I've got limited time and I'm at work. I know everybody needs to know the FULL system sp

  • How many times can i download photoshop or lightroom?

    hi how many times can I download photoshop or lightroom? I bought and downloaded them onto my lap top but want to put it onto a pc can I do that? or is it a one time down load only

  • Can not create PDF files 8

    Removed PhotoShop 5 and a few other programs the other day to create more room. Now I can't create PDF files anymore in Excel and AutoCad. When I try, it outputs to my note pad with the following: %%[ Error: undefined; OffendingCommand: setdistillerp

  • 2007 macpro1,1 badblocks New hard drive?

    My MacPro has been acting strange for over two weeks. I get error messages about extensions, startup items them my InDesign and Photoshop fail to open. I replaced all my fonts on every level. I thought it might be a virus. I've run TechTools 5 on it

  • Shocks from MacBook Pro

    I recently got a new MacBook Pro 15 and I am experience shocks on my for arm right along the edge. More so on the left side but I have even felt them on the right along the seam where the top meets the case. Any one else have this experience and what