Quantcast
Channel: Transact-SQL forum
Viewing all 12890 articles
Browse latest View live

SQL Query With Select Statement In Join Condition

$
0
0

Whenver I attempt to run this I get an error of incorrect syntax on keyword 'ON' -- is it possible to do this in ONE query?

SELECT COUNT(one.ID), one.FirstName, one.LastName, one.CompanyName, one.order_status
FROM firstDB one
INNER JOIN (
			SELECT COUNT(two.ID), two.LastName, two.FirstName, two.CompanyName
			FROM secondDB two
			GROUP BY two.LastName, two.FirstName, two.CompanyName
			HAVING COUNT(two.ID) > 1
           )
ON one.CompanyName = two.CompanyName
AND one.LastName = two.LastName
AND one.FirstName = two.FirstName
GROUP BY FirstName, LastName, CompanyName, order_status
HAVING COUNT(one.ID)>1
AND one.FirstName IS NOT NULL
AND one.LastName IS NOT NULL
AND one.CompanyName IS NOT NULL
AND one.order_status IS NOT NULL
ORDER BY one.LastName


Quick key shortcut to apply single quotes?

$
0
0

Hi All, Do you know if there is a quick key or way inside of MSFT SQL Server MGMT Studio, Query writer to apply single quotes to a large string of text?

4026, 4081, 4084, 4091, 4095, 4101, 4102, 4106, 4107, 4112, 4117, 4121, 4123, 4124, 4126, 4135, 4136, 4137, 4138, 4140, 4141, 4146, 4150, 4152, 4154, 4201, 4203, 4208, 4209, 4210, 4211, 4217, 4218, 4224, 4228, 4230, 4239, 4241, 4242, 4248, 4304, 4306, 4308, 4322

to

'4026', '4081', 4'084', '4091', '4095', '4101', '4102' ... etc.

Thanks,

:) john

Insert a Head count column query issue

$
0
0

Hello,

I have a query that includes employee data such as emp_id , name , position , dates. One employee can have multiple positions:

Emp_ID  Name   Position   Start_Date   End_date

445        John    Teacher 12-10-2012 12-08-2013

342        Ian      Musc     07-06-2012 12-08-2013

342        Ian      Teacher 22-09-2012 12-04-2013

940        Todd    Develop 23-12-2012 12-08-2013

445        Dan     IT          08-10-2012 12-08-2013

I need create aditional column that going to give me a head count(to put 1 in one row, dosn't meter where the rest of position 0 or empty ), so something like that :

Emp_ID  Name   Position   Start_Date   End_date    Headcount

445        John     Teacher 12-10-2012 12-08-2013      1

342        Ian      Musc     07-06-2012 12-08-2013       1

342        Ian       Teacher 22-09-2012 12-04-2013      0

940        Todd    Develop 23-12-2012 12-08-2013       1

445        Dan     IT          08-10-2012 12-08-2013       1

445        Dan     Teacher 08-10-2012 12-08-2013       0

445        Dan     Develop 08-10-2012 12-08-2013       0

Thank you for help

Daniel

SQL 2000 - How to avoid Table Scan in simple Select query

$
0
0

Hi All,

  we have one of SQL 2000 Server which is supporting Old application. one of select query get blocked mostly once in week some how. and it is simple select query. 

This is from view

select  "Description_Item", " Resolution_Item", "Incident_Number", "LastModified_Item", "InActive_Item" from "dbo"."Incident" where "InActive_Item" = 0

Table referencing in view has no cluster index. In execution plan Table Scan is 99% 

so what will be the best approach

to avoid table scan ?

to avoid blocking ?( occurs when users try to save changes from application) .

what are the steps should follow?

Thanks...


Please Mark As Answer if it is helpful. \\Aim To Inspire Rather to Teach

Lef Join Group on Multiple Columns

$
0
0

Hello,

I have a left join query that I want to group on two columns. If I filter and group on one column, I can get the result I want but I have to run two distinct queries, one for each result set.


Ideally I'd like to group on both columns and have all results returned in one result set.

Here is the table structure:

-- Dimension (Abbreviated for clarity)
CREATE TABLE [ALS].[DimDelinquency](
	[DelinquencyKey] [smallint] NOT NULL,
	[DelinquencyBucket] [varchar](30) NOT NULL
)

GO

-- Fact Table (Abbreviated for clarity)
CREATE TABLE [ALS].[FactSnapshot](
	[ALSFactKey] [varchar](18) NOT NULL,
	[DelinquencyKey] [smallint] NOT NULL,
	[CurrentBalance] [money] NULL,
	[TDRFlag] [varchar](1) NULL
)

GO

Here is the Query:


-- Broken Query
SELECT DelinquencyBucket, TDRFlag, COUNT(1) 'Count', SUM(IsNull(CurrentBalance, 0)) 'Total'
FROM ALS.DimDelinquency d
LEFT JOIN ALS.FactSnapshot a
	ON a.DelinquencyKey = d.DelinquencyKey AND TDRFlag IS NOT NULL
WHERE 
	MonthEndDate = '2014-06-30' 
AND A.CurrentBalance <> 0
GROUP BY DelinquencyBucket, TDRFlag
ORDER BY MAX(d.DelinquencyKey)


Here is the current output I am getting.

-- Current Result

DelinquencyBucket              TDRFlag Count       Total
------------------------------ ------- ----------- ---------------------
Current                        S       503         5019939.15
Current                        T       531         5064782.68
30-59 Days                     T       41          280788.80
60-179 Days                    T       43          297541.50
180-359 Days                   T       12          99497.49
360 Days +                     T       4           13377.90


Here is what I would like to have.


-- Desired Result

DelinquencyBucket              TDRFlag Count       Total
------------------------------ ------- ----------- ---------------------
Current                        S       503           5019939.15
30-59 Days                     S       0           0.0
60-179 Days                    S       0           0.0
180-359 Days                   S       0           0.0
360 Days +                     S       0           0.0
Current                        T       531         5064782.68
30-59 Days                     T       41          280788.80
60-179 Days                    T       43          297541.50
180-359 Days                   T       12          99497.49
360 Days +                     T       4           13377.90

Any help with this is greatly appreciated!

Thanks,

Shawn

when subquery returns null or no matching rows

$
0
0

hello,

I have a test table. when the subquery returns no matching rows, i want the outer query to return default value as 0
  create table #test(studentid integer,name varchar(10))
  insert into #test values (1,'bob')
  insert into #test values (2,'Rick')

  create table #test1  (id integer,studentid integer)
  insert into #test1 values (1,2)

  select * from #test
  select * from #test1

  select isnull(id,0)id from #test1 where studentid in (
  select studentid from #test where name like'%bob%')

I would like the resultset to return 0.

Please advice.

Thanks.

1 trigger on multiple tables

$
0
0

I am new to triggers (never coded one) and need to create a trigger (prefer 1) on multiple tables.  Basically when the trigger is run I need to capture info from whichever table is being triggered and insert a row into a history table. 

Thanks in advance.

Getting a list of all months between 2 DATE columns for a table

$
0
0

Current set:

IF OBJECT_ID('tempdb..#TEST') IS NOT NULL DROP TABLE #TEST

CREATE TABLE #TEST ( ID INT, DOB DATE, EffectiveDate DATE, TerminationDate DATE, GCode CHAR(1) ) INSERT INTO #TEST VALUES (1043,'1/1/1970','1/1/2014','4/1/2014','S'), -- Active in month Jan,Feb,March,April (1051,'1/1/1989','3/1/2014','5/1/2014','P'), -- Active in month March,April,May (1070,'1/1/2010','5/1/2014','8/1/2014','G') -- Active in month May,June,July,August SELECT * FROM #TEST

Expected result set:

ID          Month         GCode

1043      January      S

1043      February    S

1043      March         S

1043      April           S

1051      March        P

1051      April          P

1051      May          P

---- Similarly for ID 1070

This is needed for the reporting and each ID will have points associated to it, that will be a separate column that I'll be adding. The reason that I want this result set is because, the user might say, how many points did the ID have for a particular month. The points are not going to change for an ID. Please let me know how to get the expected result set



Pivot Table and null data

$
0
0

i created a pivot table using case statements 

select QUESTION_TYPE_DESC,
(case when SCALE_VALUE_DESC = 'strongly disagree' then [percent] else NULL end) as [strongly disagree],
(case when SCALE_VALUE_DESC = 'disagree' then [percent] else NULL end) asdisagree,
(case when SCALE_VALUE_DESC = 'agree' then [percent] else NULL end) asagree,
(case when SCALE_VALUE_DESC = 'strongly agree' then [percent] else NULL end) as [strongly agree]
from #temp2
group by QUESTION_TYPE_DESC, SCALE_VALUE_DESC, [percent]

Problem is that it gives me result in this form 

and i want to show result in this form 


How to define a constant in TSQL ?

$
0
0

I need to define a group of int constants and use them by a group of functions . 

so how I define a constant ?

and how to make it accessible by multiple functions ?

 

SQL Unique Key

$
0
0

hello guys, I created one table and with 15 columns on it.

Is it possible on one Table; column 1 -3 are unique columns 4 -6 - are not unique columns then 7 -10 are unique columns and 11 to 15 are not unique columns.

How do I do it?

Thank you.


Every second counts..make use of it. Disclaimer: This posting is provided AS IS with no warranties or guarantees and confers no rights.
IT Stuff Quick Bytes

Checking my Pivot Code please

$
0
0

I'll never cope with the pivot. May you check this code please guys...:

select *  from archivebilled
pivot ( sum([month charge]) for [element code] in ('august','september','october','december'))

Incorrect syntax near august

how to use select sys.synonyms to drop and create synonyms

$
0
0

select * from sys.synonyms DROP SYNONYM DATABASE1.BTXADDR; DROP SYNONYM DATABASE1.BTXSUPB; CREATE SYNONYM DATABASE1.BTXADDR FOR DATABASE2.DA2.BTXADDR; CREATE SYNONYM DATABASE1.BTXSUPB FOR DATEBASE2.DA3.BTXSUPB; TRUNCATE TABLE DATABASE2.DA2.BTXADDR; TRUNCATE TABLE DATABASE2.DA3.BTXSUPB; INSERT INTO DATABASE2.DA3.BTXSUPB SELECT * FROM DATABASE2.DA2.BTXSUPB;

The code above is the synonyms I am working with right now. But what I am trying to do is leave the drop and create synonyms variables open and then after the select * from sys.synonyms runs. Once it has loaded the table then  have it populate the drop and create synonym fields.  Also once the synonyms are found and you see what number they are pointing at I need them to change from 2 to 3 and 3 to 1 and 1 to 2.

Round function

$
0
0

Can anybody tell me about second and third argument in round function.

Here is the example

SELECT ROUND(CONVERT(MONEY,442)/CONVERT(MONEY,730), 5, 3)

This will return 0.6054. I need to round it to the nearest decimal , like

0.61.

But first please explain me about the arguments.

Thanks in advance.


ZK

Bringing back specific rows.

$
0
0

Hi SQL Gurus,

The first 3 columns are nvarchar(500) and the last one is a column i generated with a LEN function so its an INT and can have NULLs or 0. Below is the sample.  Field2 will be grouped together and if any of its corresponding field3 values do not match the rest of the Field2 values i need that row back. Thank you for any help.

Results
Results
Field1Field2Field3Field4
2Heading10010Material                                                 NylNULL
5Heading10013Jkyng0
5Heading10013Jklty0
5Heading10013Jkrty0
4Heading10012LenTTNULL
4Heading10012LenEENULL




DATA SET: Field1 -3 are nvarchar(500) and Field is an INT

Field1 Field2 Field3 Field4
1Heading 10009Type                                                                        Prim 124
1Heading 10009Type                                                                        Acc 54
1Heading 10009Type                                                                        Act 64
1Heading 10009Type                                                                        Deb 157
2Heading 10010Material                                                  Talc 94
2Heading 10010Material                                                  Nyl NULL
2Heading 10010Material                                                  Cub 249
2Heading 10010Material                                                  Alm 220
2Heading 10010Material                                                  Zirc 288
2Heading 10010Material                                                  Cer 196
2Heading 10010Material                                                  Sil 112
3Heading 10011Cut                                                                Fin NULL
3Heading 10011Cut                                                                Vry NULL
3Heading 10011Cut                                                                Crs NULL
3Heading 10011Cut                                                                Extr NULL
3Heading 10011Cut                                                                Md NULL
4Heading 10012Len TT NULL
4Heading 10012Len EE NULL
4Heading 10012Len GG 12
5Heading 10013Jk yng 0
5Heading 10013Jk lty 0
5Heading 10013Jk rty 0
5Heading 10013Jk rtu 12

Edwin Lopera




Count(*) with Partition by producing the wrong result.

$
0
0

I am new to windowing functions.

This query works fine:

Select *, Row_Number() over(Partition By FileType, INS, NEIC Order By FileType, INS, FileSize DESC) as RowNO,
    Count(*) over(Partition By FileType, INS, NEIC ) as Num_In_This_Set
    FROM NEICs

For example the first grouping has 17 items. The RowNO column, therefore, shows those rows numbered from 1 to 17. And the Count(*) column shows the number 17 repeated 17 times all the way down that first set. Great.

But if I add a second Order By clause, I get a different result for the Count(*) column - as it turns out, the values in the Count(*) column are then identical to those in the  RowNo column, almost as if I had requested the RowNo column twice in the SELECT. For me, this counts as a failure (on my part, evidently) in the sense that it's NOT what I was hoping for. But what am I doing wrong? Why would an Order By clause affect the aggregate Count() function?

Here's the query that fails:

Select *, Row_Number() over(Partition By FileType, INS, NEIC Order By FileType, INS, FileSize DESC) as RowNO,
    Count(*) over(Partition By FileType, INS, NEIC Order By FileType, INS, FileSize DESC) as Num_In_This_Set
    FROM NEICs

I'll figure out a way to get some sample data uploaded. 

How to saperate a column into three different columns

$
0
0

Hi all,

I have a column which has the values as '150/250/555','114/1254/5241','45127/521/102'. So in this way I have a column. Now I need to split this column into three different columns. Say in example '150/250/555', I need to split 150 value into one column, 250 into another column and similarly 555 into 3rd column.

I got for the first column by using this query: select substring(elt.EMPLR_LIAB_TYP_NM,1,CHARINDEX('/',elt.EMPLR_LIAB_TYP_NM)-1) From EMPLOYER_LIABILITY_TYPE elt.

This query is successfully giving me the value of 1 first column which is 150 in example '150/250/555'.

But I am little confused how to do it for 2nd and 3rd columns which should get the values 250 in 2nd column and 555 in 3rd column after '/'. Can anyone help me in this?

Thanks,

Rahul

SQL Query to find missed nunmber from each group

$
0
0

Hi,

I have a set of records called "Level" and its values are A, B, C, D.

From the below list, I want to identify the missed level for each group.

ID          Level          Type

1             A               Floor

1             B                Floor

2             A               Wind           

2             C                Wind

I need result like: [Missed level records]

ID          Level          Type

1               C             NULL     1- doesnt has C and D

1               D             NULL

2               B             NULL      2- doesnt has A and C

2               D             NULL

Pls suggest.

Regards,

-Sugumar Pannerselvam

Rebuild of index is taking lot of disk space and filling the User Database Log File very rapidly.

$
0
0

Hi,

My name is Phani, i work as a DBA for small firm, i have a question related to index rebuild maintenance plan which is scheduled for weekly once, and whenever the job runs the disk space where the log file exist is getting filled up rapidly and filling up the log file of the USER DATABASE very rapidly. I am rebuilding the indexes using the options, ONLINE=OFF and SORT_IN_TEMPDB=OFF. i am really not sure what is going wrong and where is it taking more space. Believe me once the job gets completed my log file of the user database will be 0.5TB.

Any help would be greatly appreciated.

Thanks & regards,

Phani

Sql script(*.sql) migration from Oracle to SQL

$
0
0

Hello,

I have huge scripts in Oracle that i need to migrate to SQL Server.

My question if there some tool (microsoft sql server assistant migration only for packages/views/tables) that can convert big *.sql files from oracle to sql ? or maybe there is a easier way to do it ?

Thank you very much 

Daniel

Viewing all 12890 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>