sql query to display the duplicates as per the requested output - sql-server

I have a sample input table as show below
╔═══════════╗
║ name id ║
╠═══════════╣
║ anil 3 ║
║ ashok 2 ║
╚═══════════╝
I want to get output for this table as
╔════════════╗
║ name id ║
╠════════════╣
║ anil 3 ║
║ anil 3 ║
║ anil 3 ║
║ ashok 2 ║
║ ashok 2 ║
╚════════════╝
how to achieve this using sql query?

This seems like a job for a Recursive CTE:
create table #input (name varchar(10), id int)
insert into #input values ('anil',3),('ashok',2)
;with cte as
( select a.name, a.id, a.id as countdown
from #input a
union all
select a.name, a.id, a.countdown-1
from cte a
where a.countdown-1 > 0
)
select name,id,countdown from cte
order by 1,2,3 desc
Output
name id countdown
====================
anil 3 3
anil 3 2
anil 3 1
ashok 2 2
ashok 2 1

It's tempting to go for a recursive query but this can be done simply with a tally table.
Something like this:
SET nocount ON;
IF Object_id('dbo.Tally') IS NOT NULL
DROP TABLE dbo.tally
-- Define how many rows you want in Tally table.
-- I am inserting only 100 rows
SET ROWCOUNT 100
SELECT IDENTITY(int, 1, 1) ID
INTO dbo.tally
FROM master.sys.all_columns c
CROSS JOIN master.sys.all_columns c1
-- you may use one more cross join if tally table required hundreds of million rows
SET ROWCOUNT 0
-- ADD (unique) clustered index
CREATE UNIQUE CLUSTERED INDEX pkc_tally
ON dbo.tally (id)
SELECT T2.*
FROM dbo.tally T1
CROSS JOIN table1 T2
WHERE T1.id <= T2.id
You can take a look and play around with an example on SQL Fiddle

Related

Querying SQL Server to obtain sum total using CTE and joins

I have a below query that I am trying since yesterday with some 33 records of Employee with employeeId on various conditions:
With CTE
(
select EmployeeId, and other colums with joins and conditions.
)
Now I want to join this query to obtain sum of invoices of each employee from below tables, table1 and table2.
table1 has employeeid so as my CTE has employeeid I can join it with table1
With CTE
(
select EmployeeId, and other colums with joins and conditions.
)
select *, table1.invoiceId
from CTE
left join table1 on table1.employeeid = CTE.employeeId
left join table2 on table2.invoiceid = table1.invoiceid
groupby
But my table1 only have invoices and for each such invoice there are amount spend in other table i.e table2. table2 has column "amount" that I need to sum up depending upon invoiceid.
For more clarity I am writing the table structure or output as below.
I am trying like above but they are not showing correct results
Assume CTE has
Emplyeeid empName Empaddress empcode
1 john America 121
2 sandy America 122
Now table1 has
InvoiceId EmployeeId RecordId PAyeeid
1 1 223 202
2 1 222 212
3 1 121 378
4 2 229 987
5 2 345 333
table2 has the coulmm amount that we need for each invoice of epmloyee
now table2
InvLine Invoiceid Amount
1 1 30
2 1 30
3 1 20
4 2 10
5 2 10
6 2 10
The output should be as per employe john has two invoices in table1 ie with Id 1 and 2, and for 1 and 2 invoiceds there are amounts that need to be add up
Emplyeeid empName Empaddress empcode Amount
1 john America 121 80
With CTE
(
select EmployeeId, and other colums with joins and conditions.
)
With CTE1
(
select EmployeeId,table1.invoiceid
from cte
left join table1 on table1.employeeid=CTE.employeeId
)
select sum(amount), cte1.employeeId from CTE1
left join table2 on table2.invoiceid = cte1.invoiceid
group by cte1.employeeId
but you can join the table1 in the first cte itself. There is no need to go for second cte if the first cte is simple one.

Insert data from Table1 to Table2 in SQL

I have two tables, table1 has 2 columns and table2 has 3 columns.
I would like to insert values of table1 col1 and table1 col2 into `table2 of one column.
Here is data from table1:
╔════════╦════════╗
║ Col1 ║ Col2 ║
╠════════╬════════╣
║ Value1 ║ Value2 ║
╚════════╩════════╝
Insert that into a table2 row: like
╔════════╦
║ Value1 ║
╠════════╣
║ Value2 ║
╚════════╝
How to do this with SQL?
If you want to copy each in a different row use:
INSERT INTO table2 (col1, col2)
SELECT col1, col2 FROM table1;
Or One by One
INSERT INTO table2 (col1)
SELECT col1 FROM table1;
INSERT INTO table2 (col2)
SELECT col2 FROM table1;
If you want to concatenate in the same row use
INSERT INTO table2 (col3)
SELECT col1 + col2 FROM table1;
OR
INSERT INTO table2 (col3)
SELECT col1 || col2 FROM table1;
http://www.w3schools.com/sql/sql_insert_into_select.asp

TSQL: Displaying multiple rows of results as 1 row

All,
Not quite sure how to do the following. Teaching myself SQL, working with SQL Server 2008 R2. Note that while I can perform all the select queries I like, I do not have the permissions to create drop tables in the database.
In my database, there's a table called "messages." Each message is a three letter code (e.g., 'AAA', 'AAB', etc.). Each primary key can have an arbitrary number of messages. So, for purposes of this exercise, say the table looks like this:
1 AAA
1 AAB
1 AAC
2 AAA
2 CCC
etc,
The output I would like to get is to convert this horizontal data to vertical data so I can get this:
1 AAA AAB AAC
2 AAA CCC
If relevant, the database also contains a list of all the possible message codes on a different table.
I suspect the correct answer involves PIVOT, but I am not quite sure how to get there. The closest I found is this: How to pivot table with T-SQL? However, (a) I wasn't sure how to adapt it to my situation and (b) it appears to require creating a table.
Thank you in advance.
Since your question has been edited, including both queries:
Query for expected result in Original question:
;WITH CTE AS (
SELECT T2.ID, STUFF(
(SELECT ' '+ T1.Code
FROM TableName T1
WHERE T1.ID = T2.ID
FOR XML PATH('')),1,1,'') AS CSV
FROM TableName AS T2
GROUP BY T2.ID)
SELECT TOP 1 STUFF(
(SELECT ' ' + s.Temp
FROM (SELECT CONVERT(varchar(10),ID)+' '+CSV as Temp
FROM CTE) s
FOR XML PATH('')),1,1,'') AS Result
Result:
RESULT
1 AAA AAB AAC 2 AAA CCC
See result in SQL Fiddle.
Query for expected result in Edited question:
SELECT T2.ID, STUFF(
(SELECT ' '+ T1.Code
FROM TableName T1
WHERE T1.ID = T2.ID
FOR XML PATH('')),1,1,'') AS Codes
FROM TableName AS T2
GROUP BY T2.ID
Result:
ID CODES
1 AAA AAB AAC
2 AAA CCC
See result in SQL Fiddle.
Test Data
DECLARE #TABLE TABLE(MessageID INT, Body VARCHAR(100))
INSERT INTO #TABLE VALUES
(1, 'AAA'),
(1, 'AAB'),
(1, 'AAC'),
(2, 'AAA'),
(2, 'CCC')
Query
SELECT t.MessageID,
STUFF((SELECT ' ' + Body
FROM #TABLE
WHERE MessageID = t.MessageID
FOR XML PATH(''),TYPE)
.value('.','NVARCHAR(MAX)'),1,1,'')
AS FullMessage
FROM #TABLE t
GROUP BY t.MessageID
Result Set
╔═══════════╦═════════════╗
║ MessageID ║ FullMessage ║
╠═══════════╬═════════════╣
║ 1 ║ AAA AAB AAC ║
║ 2 ║ AAA CCC ║
╚═══════════╩═════════════╝

Join based on the value to different table

Hi everyone I have a table TableC which saves primary key values from two different tables TableA and TableB. because they are primary keys from two tables I could have end up with duplicates in that tableC so when Storing values I prefixed the Primary keys with a short text to differentiate that which value is coming from which table.
Now I would like to Join this tableC with TableA and TableB to get the data from tableA and TableB
TableC :
ID_Column
1A
1B
2A
TableA:
ID_Column | Data
1 | data A 1
2 | data A 2
3 | data A 3
TableB:
ID_Column | Data
1 | data B 1
2 | data B 2
3 | data B 3
This is what I have been trying to do
select C.ID_Column, data
from tableC C
inner join tableA A
on A.ID_Column = left(C.ID_Column, 1)
inner join tableB B
on B.ID_Column = left(C.ID_Column, 1)
this will return data from both tables I want to return data from table b when ID_Column has B in the end and want to return data from tableA when ID_Column has A in the end
Thank you in advance.
Well, TableC should really have at least 2 columns, one for the id and one to identify to which table it belongs. Anyway, this could be done this way:
SELECT C.ID_Column,
ISNULL(A.Data,B.Data) Data
FROM TableC C
LEFT JOIN TableA A
ON LEFT(C.ID_Column,LEN(C.ID_Column)-1) = A.ID_Column
AND RIGHT(C.ID_Column,1) = 'A'
LEFT JOIN TableB B
ON LEFT(C.ID_Column,LEN(C.ID_Column)-1) = B.ID_Column
AND RIGHT(C.ID_Column,1) = 'B'
The results are:
╔══════════╦══════════╗
║ D_COLUMN ║ DATA ║
╠══════════╬══════════╣
║ 1A ║ data A 1 ║
║ 1B ║ data B 1 ║
║ 2A ║ data A 2 ║
╚══════════╩══════════╝
And here is a demo for you to try.
You'll obviously need to tweak this a bit, but could you consider refactoring table C just a bit. Seperate the two out and this will eliminate the calculation in the join (not a good performance tactic).
--Create Table A
IF OBJECT_ID('tempdb..#TableA') IS NOT NULL DROP TABLE #TableA
CREATE TABLE #TableA (ID_COLUMN INT, DATA VARCHAR(max))
INSERT INTO #TableA(ID_COLUMN,DATA) VALUES (1,'data A 1'),(2,'data A 2'),(3,'data A 3')
--Create Table B
IF OBJECT_ID('tempdb..#TableB') IS NOT NULL DROP TABLE #TableB
CREATE TABLE #TableB (ID_COLUMN INT, DATA VARCHAR(max))
INSERT INTO #TableB (ID_COLUMN,DATA) VALUES (1,'data B 1'),(2,'data B 2'),(3,'data B 3')
--Create Table C
IF OBJECT_ID('tempdb..#TableC') IS NOT NULL DROP TABLE #TableC
CREATE TABLE #TableC (ID_COLUMN INT, ORIGIN_TABLE CHAR(1))
INSERT INTO #TableC (ID_COLUMN, ORIGIN_TABLE) VALUES (1,'A'), (1,'B'),(2,'A')
SELECT A.ID_COLUMN, A.DATA
FROM #TableC AS C
INNER JOIN #TableA AS A ON (C.ID_COLUMN = A.ID_COLUMN)
WHERE C.ORIGIN_TABLE = 'A'
UNION ALL
SELECT B.ID_COLUMN, B.DATA
FROM #TableC AS C
INNER JOIN #TableB AS B ON (C.ID_COLUMN = B.ID_COLUMN)
WHERE C.ORIGIN_TABLE = 'B'

Join two different columns from two different tables and merge duplicates

i have two temporary table
Table 1
ID1 Name ID2 Single
----------------------------------------------------
1 ABC 1 100
2 DEF 1 200
Table 2
ID1 Name ID2 Monthly
----------------------------------------------------
3 PQR 2 500
4 LMN 2 600
1 ABC 2 700
2 DEF 2 800
I want Output
ID1 Name ID2 Single Monthly
--------------------------------------------------------
1 ABC 1 100 700
2 DEF 1 200 800
3 PQR 2 NULL 500
4 LMN 2 NULL 600
I used all Joins , Union ALL , Union nothing working
thanks in advance
Try this:
select coalesce(T1.ID1, T2.ID1) as ID1,
coalesce(T1.Name, T2.Name) as ID1,
coalesce(T1.ID2, T2.ID2) as ID2,
T1.Single,
T2.Monthly
from Table1 as T1
full outer join Table2 as T2
on T1.ID1 = T2.ID1
https://data.stackexchange.com/stackoverflow/q/121659/
If you know that all rows always will be present in Table2 you can use a right outer join instead of full join.
Hope you are using Sql Server 2008(other wise the insert statement in my query won't work). Try this one.
From the required out put, i guess you need all the values from table2 and there corresponding Single(Column name in table 1) value.
DECLARE #tempTable1 TABLE (ID1 INT,Name VARCHAR(10),ID2 INT,Single INT)
DECLARE #tempTable2 TABLE (ID1 INT,Name VARCHAR(10),ID2 INT,Monthly INT)
INSERT INTO #tempTable1 VALUES
(1 ,'ABC' ,1 ,100),
(2 ,'DEF' ,1 ,200)
INSERT INTO #tempTable2 VALUES
(3 ,'PQR' ,2 ,500 ),
(4 ,'LMN' ,2 ,600 ),
(1 ,'ABC' ,2 ,700 ),
(2 ,'DEF' ,2 ,800 );
SELECT
T2.ID1
,T2.Name
,T2.ID2
,T1.Single
,T2.Monthly
FROM #tempTable2 T2
LEFT OUTER JOIN #tempTable1 T1
ON T2.ID1 = T1.ID1
ORDER BY T2.ID1

Resources