(Not) complicated sql query ! - sql

LookupTable:
userid, mobileid, startedate, enddate , owner
1 , 1 , 12-12-2000, 01-01-2001, asd
2 , 2 , 12-12-2000, 01-01-2001, dgs
3 , 3 , 02-01-2001, 01-01-2002, sdg
4 , 4 , 12-12-2000, 01-01-2001, sdg
UserInfoTable:
userid, firstname, lastname, address
1 , tom , do , test
2 , sam , smith , asds
3 , john , saw , asdasda
4 , peter , winston , near by
Mobile:
Mobileid, Name , number, imeinumber
1 , apple , 123 , 1111111
2 , nokia , 456 , 2222222
3 , vodafone , 789 , 3333333
CallLogs:
id , Mobileid, callednumbers (string), date , totalduration
1 , 1 , 123,123,321 , 13-12-2000 , 30
2 , 1 , 123,123,321 , 14-12-2000 , 30
3 , 2 , 123,123,321 , 13-12-2000 , 30
4 , 2 , 123,123,321 , 14-12-2000 , 30
5 , 3 , 123,123,321 , 13-12-2000 , 30
6 , 3 , 123,123,321 , 14-12-2000 , 30
7 , 1 , 123,123,321 , 13-01-2002 , 30
8 , 1 , 123,123,321 , 14-01-2002 , 30
I want a query which will return me the following:
firstname, lastname, mobile.name as mobilename, callednumbers (as concatinated strings from different rows in CallLogs table) and need it for year 2000
example:
firstname, lastname, mobilename, callednumbers
tom , do , apple , 123,123,321, 123,123,321
sam , smith , nokia , 123,123,321, 123,123,321
peter , winston , apple , 123,123,321, 123,123,321
any help will be highly appreciated...
I have tried this but no sucess.. tom is getting sams calls and vice versa. I am using sql server.
SELECT DISTINCT firstname,
lastname,
mobilename,
callednumbers
FROM ([testdatabase].[dbo].[LookupTable] lt
INNER JOIN [testdatabase].[dbo].[UserInfoTable] user1
ON lt.userid = user1.id)
INNER JOIN [testdatabase].[dbo].[Mobile] device1
ON lt.mobileid = device1.id
INNER JOIN [testdatabase].[dbo].[CallLogs] log1
ON lt.mobileid = log1.deviceid
WHERE lt.starttime LIKE '%2000%'
ORDER BY firstname

DECLARE #LookupTable TABLE (
userid INT,
mobileid INT,
startedate DATETIME,
enddate DATETIME,
owner CHAR(3))
INSERT INTO #LookupTable
SELECT 1, 1, '20001212 00:00:00.000', '20010101 00:00:00.000', N'asd' UNION ALL
SELECT 2, 2, '20001212 00:00:00.000', '20010101 00:00:00.000', N'dgs' UNION ALL
SELECT 3, 3, '20010102 00:00:00.000', '20020101 00:00:00.000', N'sdg' UNION ALL
SELECT 4, 4, '20001212 00:00:00.000', '20010101 00:00:00.000', N'sdg'
DECLARE #UserInfoTable TABLE (
userid INT,
firstname VARCHAR(10),
lastname VARCHAR(10),
address VARCHAR(10))
INSERT INTO #UserInfoTable
SELECT 1, N'tom', N'do', N'test' UNION ALL
SELECT 2, N'sam', N'smith', N'asds' UNION ALL
SELECT 3, N'john', N'saw', N'asdasda' UNION ALL
SELECT 4, N'peter', N'winston', N'near by'
DECLARE #Mobile TABLE (
mobileid INT,
name VARCHAR(10),
number INT,
imeinumber INT )
INSERT INTO #Mobile
SELECT 1, N'apple', 123, 1111111 UNION ALL
SELECT 2, N'nokia', 456, 2222222 UNION ALL
SELECT 3, N'vodafone', 789, 3333333
DECLARE #CallLogs TABLE (
id INT,
mobileid INT,
callednumbers VARCHAR(50),
[date] DATETIME,
totalduration INT )
INSERT INTO #CallLogs
SELECT 1, 1, N'123,123,321', '20001213 00:00:00.000', 30 UNION ALL
SELECT 2, 1, N'123,123,321', '20001214 00:00:00.000', 30 UNION ALL
SELECT 3, 2, N'123,123,321', '20001213 00:00:00.000', 30 UNION ALL
SELECT 4, 2, N'123,123,321', '20001214 00:00:00.000', 30 UNION ALL
SELECT 5, 3, N'123,123,321', '20001213 00:00:00.000', 30 UNION ALL
SELECT 6, 3, N'123,123,321', '20001214 00:00:00.000', 30 UNION ALL
SELECT 7, 1, N'123,123,321', '20020113 00:00:00.000', 30 UNION ALL
SELECT 8, 1, N'123,123,321', '20020114 00:00:00.000', 30
SELECT DISTINCT firstname,
lastname,
device1.name AS mobilename,
stuff((select ',' + callednumbers
from #CallLogs log1
where lt.mobileid = log1.mobileid
for xml path('')), 1, 1, '') AS callednumbers
FROM (#LookupTable lt
INNER JOIN #UserInfoTable user1
ON lt.userid = user1.userid)
INNER JOIN #Mobile device1
ON lt.mobileid = device1.mobileid
WHERE lt.startedate > '20000101' AND startedate < '20010101'
ORDER BY firstname

Related

SQL Query to Calculate Monthly Budget

CREATE TABLE [dbo].[EmployeeMonthlyBudget]
(
[Name] [NVARCHAR](50) NULL,
[Budget_Day] [MONEY] NULL,
[DateCreated] [DATETIME] NULL,
[DateDeleted] [DATETIME] NULL
)
INSERT INTO [dbo].[EmployeeMonthlyBudget] ([Name], [Budget_Day], [DateCreated], [DateDeleted])
VALUES (N'SAM', 20.0000, CAST(N'2018-01-01T00:00:00.000' AS DateTime), CAST(N'2018-10-01T00:00:00.000' AS DateTime)),
(N'ROB', 10.0000, CAST(N'2018-01-01T00:00:00.000' AS DateTime), NULL),
(N'TAM', 5.0000, CAST(N'2018-01-01T00:00:00.000' AS DateTime), CAST(N'2018-05-01T00:00:00.000' AS DateTime)),
(N'TAN', 100.0000, CAST(N'2018-01-01T00:00:00.000' AS DateTime), NULL)
The above is the table structure we had to calculate monthly budget.
We are displaying the bar graph for each name how their monthly budget is.
Suppose if we take Sam his budget for Jan is 620 and Feb is 580 and so on, So we need to calculate the budget for each month until DateDeleted has value
We are able to calculate the budget per month for each Employee Name, but unable
to figure out how to calculate them for consecutive months.
Please, anyone, help me on this
How to write SQL for the above approach.
Please sample table data
Hope this helps
SELECT A.Name,A.budget_day,B.MonthName,B.totaldays*A.budget_day as MonthlySpent
FROM
[dbo].[EmployeeMonthlyBudget] A
inner join(
SELECT [Name] , DATENAME(MONTH, DATEADD(MONTH, nos.monthnos, [DateCreated])-1) AS MonthName,DAY(EOMONTH(DATEADD(MONTH, nos.monthnos, [DateCreated])-1)) as totaldays,month(EOMONTH(DATEADD(MONTH, nos.monthnos, [DateCreated])-1)) as monthOrder
from [dbo].[EmployeeMonthlyBudget]
inner join (SELECT 1 monthnos UNION SELECT 2 UNION SELECT 3
UNION SELECT 4 UNION SELECT 5 UNION SELECT 6
UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) nos on nos.monthnos <= DATEDIFF(MONTH, [DateCreated],isnull([DateDeleted],GETDATE()))+1
) B on
A.NAME=B.Name
order by A.Name,monthOrder
Try This
select name,budget_day,monthname,totalspent from
(Select j.* ,row_number () over (partition by j.name,j.monthname order by j.totalspent) as rn
from
(Select B.name,A.budget_day,MonthName,(datediff(day,[DateCreated],DefaultDate)+1)*A.budget_day as TotalSpent,monthOrder
from (SELECT
*, [Budget_Day]*DATEDIFF(day,[DateCreated],isnull([DateDeleted],GETDATE())) as TotalSpent, DATENAME(MONTH, [DateCreated]) AS MonthNameStart, DATENAME(MONTH,isnull([DateDeleted],GETDATE())) AS MonthNameEND
from
[dbo].[EmployeeMonthlyBudget]
where datecreated<=isnull(datedeleted,getdate())) A
LEFT join
(
SELECT [Name] , DATENAME(MONTH, DATEADD(MONTH, nos.monthnos-1, [DateCreated])) AS MonthName,EOMONTH([DateCreated]) as DefaultDate ,
DAY(EOMONTH(DATEADD(MONTH, nos.monthnos, [DateCreated])-1)) as totaldays,
month(DATEADD(MONTH, nos.monthnos-1, [DateCreated])) as monthOrder
from [dbo].[EmployeeMonthlyBudget]
inner join (SELECT 1 monthnos UNION SELECT 2 UNION SELECT 3
UNION SELECT 4 UNION SELECT 5 UNION SELECT 6
UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) nos on nos.monthnos <= DATEDIFF(MONTH, [DateCreated],isnull([DateDeleted],GETDATE()))
) B
on A.MonthNameStart =B.MonthName and
A.Name=B.name
UNION
Select B.name,A.budget_day,MonthName,((datediff(day,DefaultDate,isnull([Datedeleted],getdate())))+1)*A.budget_day as TotalSpent,monthOrder from
(SELECT
*, [Budget_Day]*DATEDIFF(day,[DateCreated],isnull([DateDeleted],GETDATE())) as TotalSpent, DATENAME(MONTH, [DateCreated]) AS MonthNameStart, DATENAME(MONTH,isnull([DateDeleted],GETDATE())) AS MonthNameEND
from
[dbo].[EmployeeMonthlyBudget]
where datecreated<=isnull(datedeleted,getdate())) A
inner join
(SELECT [Name] , DATENAME(MONTH, DATEADD(MONTH, nos.monthnos, [DateCreated])-1) AS MonthName,DATEADD(month, DATEDIFF(month, 0, isnull([DateDeleted],getdate())), 0) as DefaultDate,
DAY(EOMONTH(DATEADD(MONTH, nos.monthnos, [DateCreated])-1)) as totaldays,
month(EOMONTH(DATEADD(MONTH, nos.monthnos, [DateCreated])-1)) as monthOrder
from [dbo].[EmployeeMonthlyBudget]
inner join (SELECT 1 monthnos UNION SELECT 2 UNION SELECT 3
UNION SELECT 4 UNION SELECT 5 UNION SELECT 6
UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) nos on nos.monthnos <= DATEDIFF(MONTH, [DateCreated],isnull([DateDeleted],GETDATE()))+1) B
on A.MonthNameEND =B.MonthName and A.Name=B.name
UNION
SELECT B.name,A.budget_day,MonthName,totaldays*A.budget_day as TotalSpent ,monthOrder
FROM
[dbo].[EmployeeMonthlyBudget] A
inner join(
SELECT [Name] , DATENAME(MONTH, DATEADD(MONTH, nos.monthnos-1, [DateCreated])) AS MonthName,EOMONTH([DateCreated]) as DefaultDate ,
DAY(EOMONTH(DATEADD(MONTH, nos.monthnos-1, [DateCreated]))) as totaldays,
month(DATEADD(MONTH, nos.monthnos-1, [DateCreated])) as monthOrder
from [dbo].[EmployeeMonthlyBudget]
inner join (SELECT 1 monthnos UNION SELECT 2 UNION SELECT 3
UNION SELECT 4 UNION SELECT 5 UNION SELECT 6
UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) nos on nos.monthnos <= DATEDIFF(MONTH, [DateCreated],isnull([DateDeleted],GETDATE()))
where datecreated<=isnull(datedeleted,getdate())
) B on
A.NAME=B.Name
)j)k
where k.rn=1 and k.name is not null
order by k.name,k.monthOrder

Finding duplicate records in a specific date range

I have a table where I have 4 columns
Serial(nvarchar), SID(nvarchar), DateCreated(Date), CID(unique and int)
I want to find the records where there is duplicate serial and SID and where the 2 duplicate serial fall between date range of 180 days.
please help
Sample Data
Serial SID DateCreated CID
02302-25-0036 HONMD01 2017-05-01 00:00:00.000 1
02302-25-0036 HONMD01 2017-05-01 00:00:00.000 3
0264607 HONMD01 2017-05-01 00:00:00.000 65
0264607 HONMD01 2016-05-01 00:00:00.000 45
03118-09-0366 PRIVA00 2016-05-20 00:00:00.000 34
03118-09-0366 PRIVA00 2016-05-20 00:00:00.000 87
0969130 140439 2017-05-09 00:00:00.000 32
0969130 140439 2017-05-09 00:00:00.000 23
1049567 INIIL00 2017-04-12 00:00:00.000 76
create table #Test (Serial nvarchar(20), [SID] nvarchar(10), DateCreated datetime, CID int)
Insert into #Test values ('02302-25-0036', 'HONMD01', '2017-05-01 00:00:00.000', 1)
, ('02302-25-0036', 'HONMD01', '2017-05-01 00:00:00.000', 3)
, ('0264607', 'HONMD01', '2017-05-01 00:00:00.000', 65)
, ('0264607', 'HONMD01', '2016-05-01 00:00:00.000', 45)
, ('03118-09-0366', 'PRIVA00', '2016-05-20 00:00:00.000', 34)
, ('03118-09-0366', 'PRIVA00', '2016-05-20 00:00:00.000', 87)
, ('0969130', '140439', '2017-05-09 00:00:00.000', 32)
, ('0969130', '140439', '2017-05-09 00:00:00.000', 23)
, ('1049567', 'INIIL00', '2017-04-12 00:00:00.000', 76)
select distinct a.*
from
(
select t.*
from #Test t
inner join (
Select Serial, [SID]
from #Test
group by Serial, [SID]
Having count(*)>=2
) d on d.Serial = t.Serial and t.SID= t.SID
) a
full outer join
(
select t.*
from #Test t
inner join (
Select Serial, [SID]
from #Test
group by Serial, [SID]
Having count(*)>=2
) d on d.Serial = t.Serial and t.SID= t.SID
) b on a.Serial = b.Serial and a.SID= b.SID
where datediff(d,a.DateCreated, b.DateCreated)<180
Try to do this:
with cte as (
select
serial,
sid,
dateCreated,
cid,
coalesce(max(dateCreated) over(partition by serial, sid order by cid, dateCreated asc rows between unbounded preceding and 1 preceding), '1900-01-01') as last,
coalesce(min(dateCreated) over(partition by serial, sid order by cid, dateCreated asc rows between 1 following and unbounded following), '5999-01-01') as next
from table_name
)
select *
from cte
where
datediff(day, last, dateCreated) >= 180
and datediff(day, dateCreated, next) >= 180
This was a challenging question ! I have left final output with *(PreviousDate, rno) for easy understanding. Here is my way to solve :
Create table #t(Serial nvarchar(100),SID nvarchar(100),DateCreated date,CID int)
Insert into #t values
('02302-25-0036', 'HONMD01', '2017-05-01 00:00:00.000', 1),
('02302-25-0036', 'HONMD01', '2017-05-01 00:00:00.000', 3),
('0264607', 'HONMD01', '2017-05-01 00:00:00.000', 65),
('0264607', 'HONMD01', '2016-05-01 00:00:00.000', 45),
('03118-09-0366', 'PRIVA00', '2016-05-20 00:00:00.000', 34),
('03118-09-0366', 'PRIVA00', '2016-05-20 00:00:00.000', 87),
('0969130', '140439', '2017-05-09 00:00:00.000', 32),
('0969130', '140439', '2017-05-09 00:00:00.000', 23),
('1049567', 'INIIL00', '2017-04-12 00:00:00.000', 76)
Select iq2.*
FROM
(Select iq.Serial, iq.SID, iq.DateCreated, iq.CID, iq.PreviousDate,
ROW_NUMBER() OVER (PARTITION BY iq.Serial,iq.SID, CASE WHEN DATEDIFF(day, iq.DateCreated, iq.PreviousDate) <= 180 THEN 1 ELSE 0 END
ORDER BY Serial,SID) rno
FROM
(select Serial,SID,DateCreated,CID,
MAX(DateCreated) OVER (PARTITION BY Serial,SID ORDER BY Serial,SID) maxDate,
DATEADD(day,-180,MAX(DateCreated) OVER (PARTITION BY Serial,SID ORDER BY Serial,SID)) PreviousDate
from #t
)iq
)iq2
where iq2.rno <> 1
output :
Serial SID DateCreated CID PreviousDate rno
---------- ------- ---------- ---- ----------- ----
02302-25-0036 HONMD01 2017-05-01 3 2016-11-02 2
03118-09-0366 PRIVA00 2016-05-20 87 2015-11-22 2
0969130 140439 2017-05-09 23 2016-11-10 2
PS : PreviousDate is MAX PreviousDate

SQL - Start and End date based on another column

Simplified structure.
I need the two dates between a record that has an action type of 4 and an action type of 1.
The record could be in that state multiple times and I would need separate rows for their times
For example for IncidentId = 1
Row 1 - StartTime = 2017-01-01 14:00 (id:3) - End Time = 2017-01-01 20:00 (id: 5)
Row 2 - StartTime = 2017-01-01 21:00 (id:6) - End Time = 2017-01-02 11:00 (id: 9)
CREATE TABLE #returntable
(
[incidentid] INT,
[starttime] DATETIME,
[endtime] DATETIME
)
CREATE TABLE #testtableofdoom
(
[incidentlogid] INT,
[incidentid] INT,
[timestamp] DATETIME,
[actiontypeid] INT
)
INSERT INTO #testtableofdoom
( incidentlogid, incidentid, timestamp, actiontypeid )
VALUES ( 1, 1, '2017-01-01 09:00', 1 )
, ( 2, 1, '2017-01-01 11:00', 1 )
, ( 3, 1, '2017-01-01 14:00', 4 )
, ( 4, 1, '2017-01-01 16:00', 4 )
, ( 5, 1, '2017-01-01 20:00', 1 )
, ( 6, 1, '2017-01-01 21:00', 4 )
, ( 7, 1, '2017-01-02 09:00', 4 )
, ( 8, 2, '2017-01-02 10:00', 1 )
, ( 9, 1, '2017-01-02 11:00', 1 )
, ( 10, 1, '2017-01-02 14:00', 1 )
, ( 11, 2, '2017-01-02 15:00', 4 )
, ( 12, 1, '2017-01-02 16:00', 1 )
, ( 13, 1, '2017-01-02 17:00', 1 )
, ( 14, 1, '2017-01-02 18:00', 1 )
, ( 15, 2, '2017-01-02 15:00', 1 );
DROP TABLE #testtableofdoom
DROP TABLE #returntable
I used table variables instead of temp tables, and shorter column names than you, but this works:
declare #tt TABLE (
logId INT, iId INT,
dt DATETIME, atId INT
INSERT #tt (logId, iId,
dt, atId) values
(1, 1, '2017-01-01 09:00', 1),
(2, 1, '2017-01-01 11:00', 1),
(3, 1, '2017-01-01 14:00', 4),
(4, 1, '2017-01-01 16:00', 4),
(5, 1, '2017-01-01 20:00', 1),
(6, 1, '2017-01-01 21:00', 4),
(7, 1, '2017-01-02 09:00', 4),
(8, 2, '2017-01-02 10:00', 1),
(9, 1, '2017-01-02 11:00', 1),
(10, 1, '2017-01-02 14:00', 1),
(11, 2, '2017-01-02 15:00', 4),
(12, 1, '2017-01-02 16:00', 1),
(13, 1, '2017-01-02 17:00', 1),
(14, 1, '2017-01-02 18:00', 1),
(15, 2, '2017-01-02 15:00', 1)
Select s.logId startLogid, e.logId endLogId,
s.iID, s.dt startTime, e.dt endTime
from #tt s join #tt e
on e.logId =
(Select min(logId) from #tt
where iId = s.iID
and atId = 1
and logId > s.logId)
where s.aTid = 4
and ((Select atId from #tt
Where logId =
(Select Max(logId) from #tt
where logId < s.LogId
and iId = s.iId)) = 1
or Not Exists
(Select * from #tt
Where logId < s.LogId
and iId = s.iID))
This produces the following:
startLogid endLogId iID startTime endTime
----------- ----------- ---- ---------------- ----------------
3 5 1 2017-01-01 14:00 2017-01-01 20:00
6 9 1 2017-01-01 21:00 2017-01-02 11:00
11 15 2 2017-01-02 15:00 2017-01-02 15:00
it uses a self-join. s represents the first (start) record with actionType 4, and e represents end record with action type 1. Since logId increments, the end record must have higher logId than the start record, and it must be the lowest logId higher than the start records that has same iId and an atId = 1.
Select s.iID, s.dt startTime, e.dt endTime
from #tt s join #tt e
on e.logId =
(Select min(logId) from #tt -- lowest log greater than start logId
where iId = s.iID -- same iId
and atId = 1 -- with atId = 1
and logId > s.logId) -- greater than start logId
finally, the start record must be restricted to those "4" records which either have no other same incident records before it or have a "1" record immediately prior to it.
where s.aTid = 4
and ((Select atId from #tt -- atId of immed prior = 1
Where logId =
(Select Max(logId) from #tt
where logId < s.LogId
and iId = s.iId)) = 1
or Not Exists -- or there is no prior record
(Select * from #tt
Where logId < s.LogId
and iId = s.iID))
something like this?
select
d.[timestamp] as StartDate,
(select top 1 [timestamp]
from #testTableOfDoom d2
where d2.incidentid = 1 and d2.[timestamp] > d.[timestamp] and actiontypeid = 1
order by d2.[timestamp] asc
) as EndDate
from
(select
p.[timestamp],
LAG(p.actiontypeid) OVER (ORDER BY incidentlogid asc) PrevValue,
p.actiontypeid
from #testTableOfDoom p
where p.incidentid = 1) d
where d.actiontypeid = 4
and d.PrevValue <> 4

SQL query: display different group value in different column

I am trying to group by ticker, date and display their value in different columns for different tickers.
But I don't know the exact ticker name which are in my table.
original table(tickers may have other symbols besides A, B, C):
date | ticker | value
-------------------------
1 | A | 5
1 | B | 3
1 | C | 2
2 | A | 5
2 | B | 3
2 | C | 2
3 | A | 5
3 | B | 3
3 | C | 2
.......
Write the SQL query to get the result dataframe:
date | A | B | C
--------------------------------
1 | 5 | 3 | 2
2 | 5 | 3 | 2
3 | 5 | 3 | 2
As sgeddes states, this is accomplished with a pivot. You can create a pivot dynamically when you don't know all the values. I gave an example of doing just that here
https://dba.stackexchange.com/questions/98776/dynamic-select-and-place-result-in-variable-columns/98809#98809
create Table Questions
(
id int identity,
question_id int,
question_name varchar(255)
)
go
with CTEquestion
as
(
select 1 QID
union all
Select QID+1
from CTEquestion
where QID < 11
)
insert questions
select QID, 'Question'+cast(QID as varchar(50))
from CTEquestion
insert QuestionAnswers
values ('2015-04-23', 'a1', 1, 'Canswer1')
, ('2015-04-23', 'a1', 2, 'Ianswer2')
, ('2015-04-23', 'a1', 3, 'Canswer3')
, ('2015-04-23', 'a1', 4, 'Canswer4')
, ('2015-04-23', 'a1', 5, 'Ianswer5')
, ('2015-04-23', 'a1', 6, 'Ianswer6')
, ('2015-04-23', 'a1', 7, 'Canswer7')
, ('2015-04-23', 'a1', 8, 'Canswer8')
, ('2015-04-23', 'a1', 9, 'Canswer9')
, ('2015-04-23', 'a1', 10,'Canswer10')
insert QuestionAnswers
values (CONVERT(DATE, GETDATE()), 'b2', 1, 'Canswer1')
, (CONVERT(DATE, GETDATE()), 'b2', 2, 'Canswer2')
, (CONVERT(DATE, GETDATE()), 'b2', 3, 'Canswer3')
, (CONVERT(DATE, GETDATE()), 'b2', 4, 'Canswer4')
, (CONVERT(DATE, GETDATE()), 'b2', 5, 'Canswer5')
, (CONVERT(DATE, GETDATE()), 'b2', 6, 'Ianswer6')
, (CONVERT(DATE, GETDATE()), 'b2', 7, 'Canswer7')
, (CONVERT(DATE, GETDATE()), 'b2', 8, 'Canswer8')
, (CONVERT(DATE, GETDATE()), 'b2', 9, 'Canswer9')
, (CONVERT(DATE, GETDATE()), 'b2', 10, 'Ianswer10')
insert QuestionAnswers
values (CONVERT(DATE, GETDATE()), 'c3', 1, 'Ianswer1')
, (CONVERT(DATE, GETDATE()), 'c3', 2, 'Ianswer2')
, (CONVERT(DATE, GETDATE()), 'c3', 3, 'Canswer3')
, (CONVERT(DATE, GETDATE()), 'c3', 4, 'Ianswer4')
, (CONVERT(DATE, GETDATE()), 'c3', 5, 'Canswer5')
, (CONVERT(DATE, GETDATE()), 'c3', 6, 'Ianswer6')
, (CONVERT(DATE, GETDATE()), 'c3', 7, 'Canswer7')
, (CONVERT(DATE, GETDATE()), 'c3', 8, 'Canswer8')
, (CONVERT(DATE, GETDATE()), 'c3', 9, 'Canswer9')
, (CONVERT(DATE, GETDATE()), 'c3', 10, 'Ianswer10')
insert QuestionAnswers
values (CONVERT(DATE, GETDATE()), 'a1', 1, 'Canswer1')
, (CONVERT(DATE, GETDATE()), 'a1', 2, 'Ianswer2')
, (CONVERT(DATE, GETDATE()), 'a1', 3, 'Canswer3')
, (CONVERT(DATE, GETDATE()), 'a1', 4, 'Canswer4')
, (CONVERT(DATE, GETDATE()), 'a1', 5, 'Canswer5')
, (CONVERT(DATE, GETDATE()), 'a1', 6, 'Canswer6')
, (CONVERT(DATE, GETDATE()), 'a1', 7, 'Canswer7')
, (CONVERT(DATE, GETDATE()), 'a1', 8, 'Canswer8')
, (CONVERT(DATE, GETDATE()), 'a1', 9, 'Canswer9')
, (CONVERT(DATE, GETDATE()), 'a1', 10, 'Ianswer10')
-->End test data creation
--straight join
select qa.user_id, qa.question_set, q.question_id, qa.answer
from Questions q
join QuestionAnswers qa on qa.question_id=q.question_id
order by qa.user_id
--dynamic pivot
DECLARE
#questionList varchar(max)
, #maxQID int
, #qid int
select #questionList='',#maxQID = MAX(question_id), #qid= MIN(question_id)
FROM Questions
while #qid <= #maxQID
begin
set #questionList=#questionList+'['+cast(#qid as varchar(10))+']'
select #qid=min(question_id)
from Questions
where question_id > #qid
if #qid<=#maxQID
set #questionList=#questionList+', '
end
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = N'
select user_id, '+#questionList+'
from
(select q.question_id, qa.question_set, qa.user_id, qa.answer
from Questions q
join QuestionAnswers qa on qa.question_id=q.question_id) x
PIVOT
(
max(answer)
FOR question_id in ('+#questionList+')
) pvt
order by user_id'
exec sp_executesql #SQL
If you know the ticker values you can do a GROUP BY. Use CASE to do conditional SUM:
select date,
SUM(case when ticker = 'A' then value end) as A,
SUM(case when ticker = 'B' then value end) as B,
SUM(case when ticker = 'C' then value end) as C,
...
from tablename
group by date
Core ANSI SQL-99.
If the different ticker values are unknown, and may change between executions, you need product specific functionality. (The general behavior is that a SELECT always return the same number of columns - independent of table data!)

Query in oracle

SELECT PRJ_CC_id
, PROJECT_COSTCENTER_NAME
, AREA_ID
, AREA_Name
, Activity_ID
, Activity_Name
, SUM(Total)
FROM(
(
SELECT PRJ_CC_id
, PROJECT_COSTCENTER_NAME
, AREA_ID
, AREA_Name
, Activity_ID
, Activity_Name
, (SUM(mon) + SUM(tue) + SUM(wed) + SUM(thu) + SUM(fri) + SUM(sat) + SUM(
sun)) Total
FROM tr_view_masterlogentry
WHERE USER_ID = 654321
AND work_year = 2010
GROUP BY PRJ_CC_id
, PROJECT_COSTCENTER_NAME
, AREA_ID
, AREA_Name
, Activity_ID
, Activity_Name
, mon
, tue
, wed
, thu
, fri
, sat
, sun
)
UNION
(
SELECT PRJ_CC_id
, PROJECT_COSTCENTER_NAME
, AREA_ID
, AREA_Name
, Activity_ID
, Activity_Name
, Tot_Amt Total
FROM tr_view_Exchange_loghours
WHERE USER_ID = 654321
AND TO_CHAR(adj_Date, 'yyyy') = 2010
GROUP BY PRJ_CC_id
, PROJECT_COSTCENTER_NAME
, AREA_ID
, AREA_Name
, Activity_ID
, Activity_Name
, Tot_Amt
)
)
GROUP BY PRJ_CC_id
, PROJECT_COSTCENTER_NAME
, AREA_ID
, AREA_Name
, Activity_ID
, Activity_Name;
In this query when i execute it, it will make total of column 'Total' in sum function when values of both 'Total'column in union query is different like 31 and -2 and sum is 29
but when value of both 'Total' column in union query is same like 31 and 31 then it will show only 31 in sum
UNION should be UNION ALL. UNION will remove duplicates.