I have been away from SQL for a couple of months, and for the life of me cannot work out a simple way to do what i want to do.
select bu1.name,bu2.name, bu3.name, bu4.name, bu5.name
from
Sale
INNER JOIN
Sysuser on sale.userid = sysuser.userid
INNER JOIN businessunitBU1
on BU1.Businessunitid = sysuser.businessunitid
left JOIN businessunitBU2
on BU2.Businessunitid = bu1.parentbusinessunitid
left JOIN businessunitBU3
on BU3.Businessunitid = bu2.parentbusinessunitid
left JOIN businessunitBU4
on BU4.Businessunitid = bu3.parentbusinessunitid
left JOIN businessunitBU5
on BU5.Businessunitid = bu4.parentbusinessunitid
So effectively i am trying to go through the hierarchy to find all the levels. Unforunately not every entry has the same amount of levels.
period course1 course2 4 NULL Eng 4 NULL Math 4 Phys NULL 4 Chem NULL
Is there any way I can show this data this way (the order is irrelevant - row1 can be joined with row3 or row4)? period course1 course2 4 Phys Eng 4 Chem Math 4 Phys Eng 4 Chem Math
Basically, I want to be able to remove nulls.
Please let me know if any of you have come across such an issue.
Let's assume that I input a gap value of 5. I need to fill in the data between the Record 1 and Record 2 by increment of 5 as specified in the input parameter on the counter column.
For example using Record 1 and Record 2, here are the additional data needs to be inserted into the table.
1234510.1 --> Record 1 1235010.1 1235510.1 1236010.1 1236510.1 1237010.5 --> Record 2 1237510.5 1238010.5 1238510.5 123909.7 --> Record 3
Currently, I am using a cursor to read from the table and select MIN counter from the table. Then use a LOOP to fill in the gap and insert it into another table. I have over 10000 records and after fill up the gap, I might end up with even more records. Just want to see if I can get any other efficient way to achieve this.
why I want to fill in the gap, I need to calculate the average value for my record set after considering all valid data points in between.
Table Clients is master table with all records, joining against Assets table that may or may not have a matching entry.
Trying to sum an asset type against table and no matter what kind of join I do I cannot get SQL to return a NULL match against the Clients ID value. All I get back are matching rows.
Here's the SQL:
select c.cindex,SUM(a.value) AS 'Total Assets' from Clients c "the join" Assets2012 a on a.clientid=c.cindex where (c.ClientClass<=7 AND c.ClientClass<>6) AND a.assettype = 2 group by c.cindex
But no matter what type of join I do, left, right, left outer, inner, I am not getting back NULL values for client records that have no matching asset records.
Strange thing is, by removing the "and assettype=2" part I get the whole database back, with NULL's but not the range I'm looking for.
I'm working on a join between two tables where I only want one row returned... I'm matching on two columns between two tables. One of those columns in the target table could be null. I only want one record returned.
create table t1 ( oid int identity(1, 1), f tinyint )
and need way to fill it as fast as possible with say 100000 sequential values. Field f may stay = 0 but oid should be raising from row to row. How can I do it in MSSQL 2000?
How to count the number of values that exist in a row based on the values from an array of numbers. Basically the the array of numbers I want to look for are in row 1 of table [test 1] and I want to search for them and count the "out of" in table [test 2]. Excuse me for not using the easiest way to convey my question below. I guess in short I have 10 numbers and like to find how many of those numbers exist in each row. short example:
Hi, I have fields in my table which allow nulls. Is it efficient to not insert anything (the field automatically shows up as null in this case) and leave or store some value into it. The field is a smallint field?
I am running into an issue when adding data from multiple columns intoone alias:P.ADDR1 + ' - ' + P.CITY + ',' + ' ' + P.STATE AS LOCATIONIf one of the 3 values is blank, the value LOCATION becomes NULL. Howcan I inlcude any of the 3 values without LOCATION becoming NULL?Example, if ADDR1 and CITY have values but STATE is blank, I get aNULL statement for LOCATION. I still want it to show ADDR1 and CITYeven if STATE is blank.Thanks
I have a query which is returning a different result set when it is run against identical tables in 2 different environments.
The query is like:
Select F.LicenseeID, IsSpecialLicensee from FactTable F left join View_SpecialLicensee SL on F.LicenseeID = SL.LicenseeID
The Create Statement for the view is like
Create View [dbo].[View_SpecialLicensee] as Select LicenseeID, LicenseeName, IsSpecialLicensee = 1 from DimensionLicensee where LicenseeName like '%ibm%' or LicenseeName like '%cisco%' or LicenseeName like '%hp%'
In my test environment, I get the query result I expected: LicenseeID, IsSpecialLicensee 1 , 1 - (where LicenseeName = 'IBM') 2, null - (where LicenseeName = 'Juniper') 3, 1 - (where LicenseeName = 'Cisco') 4, null - (where LicenseeName = 'Microsoft') 5, null - (where LicenseeName = 'Oracle') 6, null - (where LicenseeName = 'Apple')
In my production environment, I get the following query result: 1 , 1 - (where LicenseeName = 'IBM') 2, 1 - (where LicenseeName = 'Juniper') 3, 1 - (where LicenseeName = 'Cisco') 4, 1 - (where LicenseeName = 'Microsoft') 5, 1 - (where LicenseeName = 'Oracle') 6, 1 - (where LicenseeName = 'Apple')
Ideas as to what changed gratefully received.
FYI the production environment which returned the 2nd dataset is SQL2000, I have got the result I expected in both SQL2000 and SQL2005 development environments.
I have a script that I use after some amount of data massaging (not shown). I would like to be able to change the
1) denominator value (the value 8 in line 32 of my code) based on how many columns are selected by the where clause:
where left(CapNumber,charindex('_', CapNumber)-1) = 1where capNumber is a value like [1_1], [1_4], [1_6]...[1_9] capNumber can be any values from [1_1]...[14_10] depending upon the specialty value (example: Allergy) and the final number after the equal sign is a number from 1 to 14)
2) I'd like to dynamically determine the series depending upon which values correspond to the specialty and run for each where: left(CapNumber,charindex('_', CapNumber)-1) = n. n is a number between 1 and 14.
3) finally I'd like to dynamically determine the columns in line 31 (4th line from the bottom)
If I do it by hand it's 23 * 14 separate runs to get separate results for each CapNumber series within specialty. The capNumber series is like [1_1], [1_2], [1_3],[1_4], [1_5], [1_6], [1_7], [1_8],[1_9] ... [8_4],[8_7] ... [14_1], [14_2],...[14_10] etc.
Again, the series are usually discontinuous and specific to each specialty.
Here's the portion of the script (it's at the end) that I'm talking about:
--change values in square brackets below for each specialty as needed and change the denom number in the very last query.
if object_id('tempdb..#tempAllergy') is not null drop table #tempAllergy select * into #tempAllergy from dbo.#temp2 T
[Code] ....
If I were to do it manually I'd uncomment each series line in turn and comment the one I just ran.
I want to aggregate to monthly values for the reading. I want to display Reading value for Oct 2010, November 2010 likewise My question is simple and I have tried to follow the etiquette.
IF OBJECT_ID('TempDB..#mytable','U') IS NOT NULL DROP TABLE #mytable
--===== Create the test table with
CREATE TABLE #mytable ( meterID INT PRIMARY KEY, Readingdate DATETIME, reading real )
--===== Setup any special required conditions especially where dates are concerned
SET DATEFORMAT DMY SELECT '4','Oct 17 2013 12:00AM','5.1709' UNION ALL SELECT '4','Oct 17 2013 12:15AM','5.5319' UNION ALL SELECT '4','Nov 17 2013 12:00AM','5.5793' UNION ALL SELECT '4','Nov 17 2013 14:00AM','5.2471' UNION ALL SELECT '5','Nov 17 2013 12:00AM','5.1177' UNION ALL SELECT '5','Nov 17 2013 14:00AM','5.5510' UNION ALL SELECT '5','Dec 17 2013 15:00AM','5.5128', UNION ALL SELECT '5','Dec 17 2013 16:00AM','5.5758' UNION ALL
Output should display as
MeterId Period Reading
4 Oct 13 10.20 4 Nov 13 10.40 5 Oct 13 10.20 5 Nov 13 10.40 4 Dec 13 11.15
To give you some context we have a new amendments application (nothing fancy, excel based with SQL Server back end) that allows users to submit amendments to product data (Product Info, PO Prices, Dates etc.). There is also an admin tool that a team uses to action these amendments in the various systems.
The old version of this tool, users submitted amendments by style and could if need be submit multiple amendments against one product at the same time. The new tool, I believe for audit reasons, users submit by amendment type, so for example I would submit a cost price change for a given style.
The issue now is that on the occasions where a user has multiple amendments, they now come through separately. So cost price would be Amendment 1 and a date change would be amendment 2 even though they could be the same product. This could potentially mean that the admin team would be duplicating work if the paperwork is updated and sent after each amendment, whereas before they would make both changes and only send the paperwork once.
Having not built either of these tools, I've been tasked with trying to fix this, my two thoughts being either to amend the user form to somehow capture/ allow users to submit amendments together or try to use the existing data and doing the grouping dynamically in the back end. Use that lag to look at grouping any submitted amendments that occur within 30mins of the first occurrence of that style
This grouping would then be given a joint time so when the 'time lag' period passes the amendments will be visible together.I've tried a few things and a few head on desk moments trying to get a set based approach but haven't been able to get where i want, its either an issue where amendments span an hour, such as 9:59 and then 10:03 or grouping together amendments that happen after the 30mins of the first one.
Here is some sample data
USE FF_Winning_Together; IF OBJECT_ID(N'tempdb..#AmendTest',N'U') IS NOT NULL DROP TABLE #AmendTest; CREATE TABLE #AmendTest ( AmendmentIDINT IDENTITY(1,1)NOT NULL, StyleCHAR(1)NOT NULL, AmendmentStatusVARCHAR(10)NOT NULL, DTDATETIMENOT NULL
I have 2 identical tables one contains current settings, the other contains all historical settings.I could create a union view to display the current values from table A and all historical values from table B, butthat would also require a Variable to hold the tblid for both select statements.
Q. Can this be done with one joined or conditional select statement?
DECLARE @tblid int = 501 SELECT 1,2,3,4,'CurrentSetting' FROM TableA ta WHERE tblid = @tblid UNION SELECT 1,2,3,4,'PreviosSetting' FROM Tableb tb WHERE tblid = @tblid
When i do a select on my emplee table for rows with null idCompany i dont get any records
I then try to modify the table to not allow a null idCompany and i get this error message:
'Employee (aMgmt)' table - Unable to modify table. Cannot insert the value NULL into column 'idCompany', table 'D2.aMgmt.Tmp_Employee'; column does not allow nulls. INSERT fails. The statement has been terminated.
I have a problem with trying to pull postcodes from a table when I have a lookup table which provides me with a StartPostCode and an EndPostCode.
For instance if, in the input table I have a postcode BETWEEN two values eg: CV1 and CV10 I want to get a third value from the look up table.My problem is my query seems to bring two values back even if the postcode is between the ranges specified.To reproduce the problem first create the tables and populate with the data.
USE [CTSStaging] GO /****** Object: Table [dbo].[st_StobartPostCode] Script Date: 10/23/2014 12:42:25 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON
is there an elegant way to use one equals sign in a where clause that returns true when both arguments are null, and returns true when neither is null but both are equal and returns false when only one is null?
table2 is intially populated (basically this will serve as historical table for view); temptable and table2 will are similar except that table2 has two extra columns which are insertdt and updatedt
process: 1. get data from an existing view and insert in temptable 2. truncate/delete contents of table1 3. insert data in table1 by comparing temptable vs table2 (values that exists in temptable but not in table2 will be inserted) 4. insert data in table2 which are not yet present (comparing ID in t2 and temptable) 5. UPDATE table2 whose field/column VALUE is not equal with temptable. (meaning UNMATCHED VALUE)
* for #5 if a value from table2 (historical table) has changed compared to temptable (new result of view) this must be updated as well as the updateddt field value.
I have two select statements; one for open purchase orders, one for open customer orders. I would like to be able to combine the query based on i.item in the top statement joined with c.item from the bottom statement. The i.item is related to a specific c.item, but they do not have the same values. In this case I want to join based on.
p.item=i.item where 1001099548=1001099550 84162359=84198545 84532300=84532293 47547523=47547951 305545A3=87433653 87444977=87444975
left side coming from p.item = right side coming from c.item.
Here are my statements.
--#1 OPEN PO's SELECT p.item ,(p.qty_ordered-p.qty_received) as POQtyRemaining ,i.item ,i.qty_on_hand ,p.po_num
I am working on some data that is JOINing to another table. Not a big thing. In the child table, there are different values for a single ID. I want to be able to select the Max ColorID that is Not Null, for each distinct CarID. The CarID is what I am joining the other table with. I need selecting the distinct row with the Max ColorID that is not Null. All this data is made up, so nothing looks logical in the design.
DECLARE @ColorList TABLE ( CarID float , ColorID int ) INSERT INTO @ColorList SELECT 1.55948815793043E+15, 9 UNION ALL SELECT 1.55948815793043E+15, 27 UNION ALL
Now for columns Week1 to week3 if value is 0 then i want to display by searching next week value, if it is also 0 then go for next week and if value found there then display instead of zero. so my output would be as below instead of above.
I've tried all sorts of code i.e. cross apply, running totals, etc. Cannot get this to work. I am trying to add a previous row value but only doing it for each group.
I would like to set the start time of the next row to be equal to the previous row time + duration. I know the start time of each group of 'Items' when the 'Sequence' number = 1. The last 'duration' value in the group would be ignored.
I am currently reading through Itzik Ben-Gan's "Microsoft SQL Server 2012 High-Performance T-SQL using Windows Functions." In attempt to test the SUM OVER() function in SQL 2008 because that's what I've got. I do not currently have sample data (trying to generate it has become a major PITA), but I have some pseudocode.
My current code (actual production code) pulls a bunch of ITD (inception to date) contracts then calculates a certain dollar amount based on monthly changes. Not all contracts have values during a given month, so here's what I cobbled together a few months ago. (Per our finance team, these numbers ARE accurate).
WITH MonthlyVals AS (SELECT ContractID, SUM(Col1 - (Col2 + Col3 + Col4 + Col5)) AS MyTotal FROM MyTable WHERE MyDate >= @ThisMonthStartDate AND MyDate <= @ThisMonthEndDate AND StatementType IN (8,4,2)
[code]....
To test the totals, I also added a COMPUTE SUM(MyTotal) to the end of each query. (Yes, I know COMPUTE is deprecated. Just wanted a quick check.). The difference between the two bits of code was over 68k, with the SUM OVER() code coming up with a total higher than the CTE code. I know CTE code is correct for a fact. It went through extensive testing before getting put in Production. Is it the way I joined the table for the SUM OVER()? Or is it the use of PARITION BY?
Trying to use LIKE / NOT LIKE to identify values that contain any alphanumeric characters outside of A-Z e.g £%$^&*_-{[@ etc etc
The field should contain only values between A-G with a numberic e.g ABCD1234567... but some rows have characters such as above, some have spaces (weeps) , and some have letters outside the A-G range ....
I have a small problem with a join clause, because i need to return all values from my table BL:
my code is:
SELECT cast(0 as bit) as 'Escolha',data, contado , ollocal ,origem, ousrdata,ousrhora FROM ( SELECT noconta,banco, u_area FROM BL
[code]....
In fact, i need to return 2 accounts (16,35) - x.NOCONTA IN (16,35), but I know that the problem is on the WHERE clause.How can do that, because i need all the condition on WHERE clause regarding my table OL, but also, i need to return my two accounts (16,35).
The 2 digit number that appears on line 1, 7 and 13 (only in this example) i need to have added to the begin of each value below it until the next 2 digit number is encountered. The desired result set would look like:
I have a column containing values for different languages. I want to cut out the values per languate in a seperat column.
The syntax is a 2 letter country code followed by : the value is contained in double quotes. each languate is separated by a ; (except for the last one)
EX ur English, Dutch and Swedish:US:"Project/Prescription sale";NL:"Project/specificatie";SW:"Objektsförsäljning"
The result would Be column header US with value Project/Prescription sale
next column header NL with value Project/specificatie etc.
Here are table examples:
IF OBJECT_ID('[#SALETYPE]','U') IS NOT NULL DROP TABLE [#SALETYPE]
CREATE TABLE [#SALETYPE]( [SaleType_Id] [int] NOT NULL, [name] [nvarchar](239) NOT NULL,