Basically rotate it through 90 degrees clockwise and flip it over :)
I'm pretty sure this is done by using a crosstab query and or a
derived table or temp table. The problem is I use a crosstab query to
get the original data into the first format. I've been struggling
trying to get the ouptput into the second format for over a day now
and just can't seem to get it to work. Can anyone give me any pointers
on the general solution to this?
select convert(datetime,task_date) as date, sum(Case status_id when 1000 Then 7 else 0 end) as Programming, sum(Case status_id when 1016 Then 5 else 0 end) as Design, sum(Case status_id when 1752 Then 4 else 0 end) as Upload, sum(Case status_id when 1032 Then 2 else 0 end) as Testing, sum(Case status_id when 1128 Then 1 else 0 end) as Meeting, sum(Case status_id when 1272 Then 1 else 0 end) as Others from task_table where user_id='EMP10028' and task_date='9/11/2006' group by task_date union select convert(datetime,task_date) as date, sum(Case status_id when 1000 Then 7 else 0 end) as Programming, sum(Case status_id when 1016 Then 5 else 0 end) as Design, sum(Case status_id when 1752 Then 4 else 0 end) as Upload, sum(Case status_id when 1032 Then 2 else 0 end) as Testing, sum(Case status_id when 1128 Then 1 else 0 end) as Meeting, sum(Case status_id when 1272 Then 1 else 0 end) as Others from task_table where user_id='EMP10028' and task_date='9/12/2006' group by task_date union select convert(datetime,task_date) as date, sum(Case status_id when 1000 Then 7 else 0 end) as Programming, sum(Case status_id when 1016 Then 5 else 0 end) as Design, sum(Case status_id when 1752 Then 4 else 0 end) as Upload, sum(Case status_id when 1032 Then 2 else 0 end) as Testing, sum(Case status_id when 1128 Then 1 else 0 end) as Meeting, sum(Case status_id when 1272 Then 1 else 0 end) as Others from task_table where user_id='EMP10028' and task_date='9/13/2006' group by task_date union select convert(datetime,task_date) as date, sum(Case status_id when 1000 Then 7 else 0 end) as Programming, sum(Case status_id when 1016 Then 5 else 0 end) as Design, sum(Case status_id when 1752 Then 4 else 0 end) as Upload, sum(Case status_id when 1032 Then 2 else 0 end) as Testing, sum(Case status_id when 1128 Then 1 else 0 end) as Meeting, sum(Case status_id when 1272 Then 1 else 0 end) as Others from task_table where user_id='EMP10028' and task_date='9/14/2006' group by task_date union select convert(datetime,task_date) as date, sum(Case status_id when 1000 Then 7 else 0 end) as Programming, sum(Case status_id when 1016 Then 5 else 0 end) as Design, sum(Case status_id when 1752 Then 4 else 0 end) as Upload, sum(Case status_id when 1032 Then 2 else 0 end) as Testing, sum(Case status_id when 1128 Then 1 else 0 end) as Meeting, sum(Case status_id when 1272 Then 1 else 0 end) as Others from task_table where user_id='EMP10028' and task_date='9/15/2006' group by task_date union select convert(datetime,task_date) as date, sum(Case status_id when 1000 Then 7 else 0 end) as Programming, sum(Case status_id when 1016 Then 5 else 0 end) as Design, sum(Case status_id when 1752 Then 4 else 0 end) as Upload, sum(Case status_id when 1032 Then 2 else 0 end) as Testing, sum(Case status_id when 1128 Then 1 else 0 end) as Meeting, sum(Case status_id when 1272 Then 1 else 0 end) as Others from task_table where user_id='EMP10028' and task_date='9/16/2006' group by task_date
My out put is Date Program Design Upload Testing Meeting Others 2006-09-11 00:00:00.000 42 0 0 8 2 1 2006-09-12 00:00:00.000 77 0 0 4 0 0 2006-09-13 00:00:00.000 56 0 0 8 0 1 2006-09-14 00:00:00.000 63 0 0 6 0 1 2006-09-15 00:00:00.000 63 0 0 6 0 1
Now i want in below format 2006-09-11 2006-09-11 etc
I have the following structure with remote select permissions; I cannot create temp tables or use stored procs:
tblEvent with event_pk, eventName tblReg with reg_pk, event_fk, person_fk, organization_fk
I'm currently using a case statement to get counts for these categories: case when c.person_fk is Null and c.organization_fk is not null then 'Employer' when c.person_fk is Not Null and c.organization_fk is null then 'Individual' when c.person_fk is not Null and c.organization_fk is not null then 'Both' else 'Unknown' end
But I need some kind of count (0) for every category. I've used a cross-join, group by in the past - but what do you do if you don't have a table? For example, the end result when selecting event_pk=(112,113) would be:
From the above I wanted to create a pivot table, from there I want to pass the column values through to a UDF
XSection (Width, Height, Flange, Leg, LegCount)
I tried the following to get a pivot table but it does not give a single row but 5.
SELECT CASE sp.PropertyName WHEN 'Width' THEN tsp.PropertyValue ELSE 0 END AS Width, CASE sp.PropertyName WHEN 'Height' THEN tsp.PropertyValue ELSE 0 END AS Height, CASE sp.PropertyName WHEN 'Flange' THEN tsp.PropertyValue ELSE 0 END AS Flange, CASE sp.PropertyName WHEN 'Avg. Leg Width' THEN tsp.PropertyValue ELSE 0 END AS Leg, CASE sp.PropertyName WHEN 'Leg Count' THEN tsp.PropertyValue ELSE 0 END AS LegCount FROM tbTemplateShapeProperties AS tsp INNER JOIN tbShapeProperties AS sp ON tsp.fkProperty = sp.Property WHERE tsp.fkTemplate = 1
So, this leaves me with one question, even if I was to get this to work, is is possible to then extract the values and pass them through to the UDF within the same stored proc?
Hi, I wanna know is there any advantage of perf gain when using Derived Tables over Temp Tables, advice me which one is better to use. Can I create Indexes and Insert/Update records into Derived Tables.
Hi All, The problem is about cross reference. 1. I have a third party cross reference store procedure SimpleXTab CREATE PROCEDURE [dbo].[SimpleXTab2] @XField varChar(50), @XTable varChar(100),@XWhereString varChar(250), @XFunction varChar(10), @XFunctionField varChar(50), @XRow varchar(300),@ResultTable varchar(100) ASDeclare @SqlStr nvarchar(4000)Declare @tempsql nvarchar(4000)Declare @SqlStrCur nvarchar(4000)Declare @col nvarchar(100) set @SqlStrCur = N'Select [' + @XField + '] into ##temptbl_Cursor from [' + @XTable + '] ' + @XWhereString + ' Group By [' + @XField + ']' /* select @sqlstrcur */exec sp_executesql @sqlstrcur
declare xcursor Cursor for Select * from ##temptbl_Cursor open xcursor Fetch next from xcursor into @Col While @@Fetch_Status = 0Begin set @Sqlstr = @Sqlstr + ", " set @tempsql = isnull(@sqlstr,'') + isnull(@XFunction + '( Case When ' + @XField + " = '" +@Col + "' then [" + @XFunctionField + "] Else 0 End) As [" + @Col + "]" ,'') set @Sqlstr = @tempsql Fetch next from xcursor into @Col End /* Select @Sqlstr as [mk], len(@sqlstr) as [leng] */ set @tempsql = 'Select ' + @XRow + ', ' + @Sqlstr + 'into ' +@ResultTable+' From ' + @XTable + @XWhereString + ' Group by ' + @XRowprint @tempsql set @Sqlstr = @tempsql Close xcursor Deallocate xcursor set @tempsql = N'Drop Table ##temptbl_Cursor' exec sp_executesql @tempsqlprint @tempsql /* Select @Sqlstr as [mk], len(@sqlstr) as [leng] */print @sqlstr exec sp_executesql @Sqlstr if @@rowcount = 0 select 'No Records found'GO 2. I've use this store procedure for many cross reference successfully. But this time my cross reference value (resultcode) is a varchar which cannot be convert to int or decimal in sql, Probably, you've noticed that the fourth parameter is a function. how can i modify SimpleXtab to avoid using math function but still can generate cross reference. exec simplextab2 'Sequence','##tbltempreport',' ','sum','resultcode','Parameter' ,'dbo.resultcodetable'
I am currently building a website to deal with different product information and sales with php. I am using SQL to sort the database and pull out information.
The final thing i need to do is work out the total revenue of each product however the problem i am having is that the 'Price' column and 'SalesVolume' column are in two different tables and they need to be multiplied together.
The two tables and column headings are as follows:
Product ID Name Price
MonthlySales ID ProductCode Month Year SalesVolume
(ID and ProductCode are linked together in a relationship)
I cannot see anything wrong with the syntax in my query however i believe there is.
Here is the query I am using:
Code: "SELECT SUM(Products.Price * SUM(MonthlySales.SalesVolume)) as revenue FROM Products INNER JOIN MonthlySales ON(Products.ProductCode = MonthlySales.id) GROUP BY Products.ProductCode";
Is it possible to create cross table query via SQL Express 2005 since it's possible to do with MS Access?
Sample query in MS Access:
TRANSFORM Count([tip]) AS [The Value] SELECT [sifra], [naziv] FROM naselja GROUP BY [sifra], [naziv] PIVOT [opstina] Is there any soultion how to make same or at least identical SQL query expression which will behive like MS Access ones?
Hi, I have built a database for a university project, but am having trouble with the SQL syntax for inserting derived data from a calculation into a table. At present my SQL is; INSERT INTO MemberPayment (TotalCharge) VALUES ( [Total] ) SELECT ((MileageHistory.MileageUrban * Vehicle.EmissionsPerGramUrban) * 0.05) + ((MileageHistory.MileageCountry * Vehicle.EmissionsPerGramUrban) * 0.05) AS 'Total' FROM [NeuCar].[dbo].[MileageHistory] JOIN [NeuCar].[dbo].[Vehicle] ON MileageHistory.Registration = Vehicle.Registration JOIN [NeuCar].[dbo].[Member] ON Vehicle.UserName = Member.UserName WHERE Member.UserName = 'wenger1' AND (MileageHistory.[Date] >= CURRENT_TIMESTAMP - 30); Would anybody be able to point out where I am going wrong? I would very much appreciate any advice, Kind regards, Chima
I got an error as follows: Derived table 'A' is not updatable because a column of the derived table is derived or constant. when I tried to run this query: update A set MonthsUnbilled =99999888 FROM (select MonthsUnbilled from dbo.vw_MasterView WHERE (RecordID =8377396)) A This is a simplified query in order to pinpoint the culprit. I know I don't need to use a derived table if the real query is this simple.
Below is my sql, i am getting error msg "Incorrect sytax near 'Votes'." Can anyone tell me what im doin wrong?
UPDATE #TblExposure SET E.Unity = ( SELECT -- DealId ,DocketId, CASE Participant2 WHEN nullTHEN 'NA' ELSE CASE WHEN Participant2-Vote2 =0 THEN 'Yes' ELSE 'No' END END AS Unanimous1 FROM #tblVoting ) Votes FROM #tblExposure E INNER JOIN Votes ONVotes.Dealid = E.Dealid AND Votes.DocketId =E.DocketId
OBJECTIVE:THE QUERY SHOULD GIVE ME THE FIELDS I MENTIONED IN THE FIRST QUERY WITH THE CONDITIONS BELOW. CONDITION 1: RateReview field should have yesterday's date CONDITION 2: Email will be send to customer only once so Customer_GUID is UniqueIdentifier CONDITION 3: Customer shouldnt' have opted to get out from receiving any email so Termination field should be NULL ONe Customer can have many transwactions Is there any way i write the code specifying that no email should be sent more than once evereven if customer buys 10 tickets. Only one email sent so i need to specify that if this email has gone to particulare CUSTOMER_GUID then Ignore that record and do not send any email. This would be done by some tool known as StrongMail. SELECT CAST(a.Transaction_GUID AS varchar(36)) as Transaction_GUID, CAST(a.Customer_GUID AS varchar(36)) as Customer_GUID, Film_id as MovieId, First_nm as FirstName, Last_nm as LastName, Email_nm as EmailAddress FROm Table1 where RateReview_dm >= dateadd(day, datediff(day, 0, getdate()), -1) -- Greater or same as Yesterday day and RateReview_dm < dateadd(day, datediff(day, 0, getdate()), 0) -- Less than today's date and and Terminate_dm is null (I don;t know what condition to give that same customer good should not be send email again if send once) i don't know whether i need to create a derive table or it can work without drive table
I've created this:SELECTc.ProjectID,Count(c.ID) as 'Registrants',Count(dt.Hits) as 'Submissions'FROMCME_TBL cJOIN(SELECT ProjectID, Count(*) as Hits FROM CME_TBLWHERE evalDate Is Not NULL OR testDate Is Not NULLGROUP BY ProjectID) dtON c.ProjectID = dt.ProjectIDGROUP BYc.ProjectIDORDER BYc.ProjectIDand I get this:ProjectID Registrants Submissions--------- ----------- -----------adv_104699 99adv_1047185 185adv_110566 66boh_107134 34Instead, I want this:ProjectID Registrants Submissions--------- ----------- -----------adv_104699 14adv_1047185 82adv_110566 17boh_107134 12The "ProjectID" and "Submissions" columns are produced when I run thederived table (dt, above) as a standalone query. By the same token,the "Project ID" and "Registrants" columns are produced when I run the"outer" query, above.Am I on the right track here?TIA,-- Bill
I have an application that has two different database backends, one is SQL Server Compact Edition and the other is SQL Server. The reason is because the application may run at home on one of our sales agent's computers or here in the office.
I have a query that uses a derived table and works just fine in SQL Server, however when I run it in the compact edtion (having the exact same table structures) it will not run. My question is...does the Compact Edtion or the Mobile Edition allow derived tables. If not is there a way to work around this? I will happily give an example if it will help.
I have some questions on derived table. Below is my situation.
Table order, there are 40 columns and it has indexes for productID and addressID Table product, there are 15 columns and it has index for productID Table address, there are 20 columns and it has index for addressID
Query A ------- select C.address, C.area, B.productname, B.category, A.qty, A.price from order A join product B on A.productID = B.productID join address C on A.addressID = C.addressID
Query B ------- select C.address, C.area, B.productname, B.category, A.qty, A.price from (select qty, price, productID, addressID from order) A join (select productID, productname, category from product) B on A.productID = B.productID join (select addressID, address, area from address) C on A.addressID = C.addressID
Will I loss the indexing when using derived table? Why query B performance is much better than query A?
Hi,I got another question here:I want to use query like this:SELECT * FROM (sp_lock AS T) WHERE objectID = ...The purpose is that I want to query the result set returned by sp_lockusing derived table, but it doesn't work. Why?Thanks,Baihao--Posted via Mailgate.ORG Server - http://www.Mailgate.ORG
I am working for my client on SQL 2005 Enterprise & observed a strange behaviour. Consider a table(EMPTABLE) as below:
PK, INT
VARCHAR
EMPID
EMPNAME
1
A
2
B
3
C
4
D
5
E
6
F
7
G
8
H
9
I
10
J
Now, I wanted the 5th highest EMPID from 2 from the table. Now, we know that the SQL
SELECT TOP 6 EMPID FROM EMPTABLE WHERE EMPID >=2 should (from all other possibilities) return me the desired value as the last row of the output table. I tried to get this in a derived table & get the MAX value i.e.
SELECT MAX(EMPID) FROM ( SELECT TOP 6 EMPID FROM EMPTABLE WHERE EMPID >=2 ) der
But this returns me 10, when I would've thought 7 was the expected answer
I remodified my query as mentioned below to strangely get 7 as the result... SELECT MAX(EMPID) FROM ( SELECT TOP 6 EMPID FROM EMPTABLE WHERE EMPID >=2 ORDER BY EMPID ASC ) der
How did the ORDER BY hep it???
Also, if I use SELECT MAX(EMPID) FROM ( SELECT TOP 6 EMPID FROM EMPTABLE WHERE EMPID >2 ) der
I get the same result without having to specify the ORDER BY in my derived TABLE...
I tried looking for similar threads. But nothing could explain this to me...
If anyone knows what I am not able to understand, please let me know.
Hello, I have an SQL problem that is hard to describe so here's an example scenario:
a) company has a personnel database, identifying each person in the company and their assigned role(s).
b) tblPersonnel has a row per person, key is 'PersonnelID' c) tblRoles is a list of all the roles in the company (administrator, clerk, shipper, truck-driver, etc.), key is 'RoleID'
d) tblPersonnelRoles is a cross-reference of all the roles assigned to each person - in simple format of:
PersonnelID | RoleID
Given all the above, I need to have a select statement that produces one row per person, and list all the fields from tblPersonnel AS WELL AS identifies each role assigned to the person.
I'm no SQL guru .. is this even possible?
I know there are alternative solutions (e.g., to write code that for each Personnel does a lookup in Roles) but for one particular situation I need a single SQL statement, or even Stored Procedure.
Thanks in advance, Rick Piovesan Detaya Corp Aurora, Ontario, Canada
Relative SQL newbie here......this is probably easy, but....Lets say I have a table (MainTable) that stores a list of input table names,a primary key (PKey), and a field called "Configured" for each one. Each ofthese input tables also contain a field called "Configured", which is set totrue or false in another process based on an OrderNumber. (So an order'sinputs are stored in several input tables, and the MainTable is a summarytable that shows which input tables have been configured for any givenOrderNumber).What I need to do is open each input table, and look for a record containinga specific OrderNumber and where Configured=true. If a record is found, Ineed to update the Configured field for that table in the MainTable, andthen move on to the next sub-table.The way I'm doing it now is with simple SQL and loops. Here is the basiccode (ASP):*****************************************OrderNumber = "562613" ' the current order that is being processed' reset all configured flagssql = "UPDATE MainTable SET Configured = 0"conn.execute sql, , &H00000080' get list of all tablenamessql = "SELECT InputTableName, PKey FROM MainTable WHERE InputTableName <>'---'"set rsTableNames = conn.execute(sql)while not rsTableNames.eof' test each input table for configured flagsql = "SELECT Configured FROM " & rsTableNames("InputTableName")& _" WHERE Configured = 1 AND OrderNumber = '" & OrderNumber &"'"set rs = conn.execute(sql)If Not rs.EOF Then' update the main tablesql = "UPDATE MainTable SET Configured = 1 WHERE PKey='" &rsTableNames("PrimaryKey") & "'"conn.execute sql, , &H00000080end ifset rs = nothingrsTableNames.movenextwend*****************************************There has to be a faster way.. I think.... maybe something that could bewritten as a stored procedure? I use a similar technique in a couple ofother places and it's a bit of a performance hit, especially as the numberof input tables grows.TIA!Calan
I'm trying not to use a temp table, but i may have to do so.. I'm using sql2005 for this case.
i have a derived table that makes the following results:
ID Status Name
2 1 "A"
2 2 "B"
I want to get the following:
ID Name1 Name2
2 "A" "B"
but like I said before, I can't repeat the query that gets the first 2 rows, as it's pretty invovled. a temp table is the best route I see right now, but I just wanted to be sure I'm not missing something. If I've aliased it as 'results', is there a way to alias results again as something else? or maybe a trick with CTEs? I will try that! It seems promising.
I'm trying not to use a temp table, but i may have to do so..
i have a derived table that makes the following results:
ID Status Name 2 1 "A" 2 2 "B"
I want to get the following: ID Name1 Name2 2 "A" "B"
but like I said before, I can't repeat the query that gets the first 2 rows, as it's pretty invovled. a temp table is the best route I see right now, but I just wanted to be sure I'm not missing something.
In my TSQL code i use a derived table to extract the value of account 321 to compare if they are the same that the SUM of my line invoice cost multiply by quantity line : Sum(fi.ecusto*qtt)
This is my script:
SELECT ft.ndoc [Doctype],ft.fno [Docnr] , Sum(fi.ecusto*qtt) [totalcostof my Invoiceline], xctb.conta [accountancy account], sum(Case when ft.tipodoc = 1 then Xctb.ecre else Xctb.edeb end) as [Value of Cost of invoice in accountancy], [DIF] = Sum(fi.ecusto*qtt) - Sum(Case when ft.tipodoc = 1 then xctb.ecre else xctb.edeb end)
[Code] ....
My problem is if i have more than on line on my invoice, for example 2 lines, the value of column [Value of Cost of invoice in accountancy] are duplicated, for 3 line invoice the value are multiply by 3.
When my colleague makes any change to a query containing a derived table, the word 'WITH' followed by a lot of graphical characters appears after the alias, rendering the query unusable. We have tried this with various existing and new, simple queries, all to no avail. We are editing the queries in Visual Studio 2003, and he does not get this effect when using Visual Studio 2005. I can edit the query in 2003 on my laptop with no ill effects.
I have discovered what looks like a bug in the optimiser. I've posted it at https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=288243 but I wonder if any of you with SQL 2005 RTM, 2005 SP1 or 2008 CTP could confirm when this was introduced and whether it is still an issue?
Code Snippet
-- Bug report
-- 2007/07/19
-- Alasdair Cunningham-Smith
-- alasdair at acs-solutions dot co dot uk
set nocount on
go
-- example date in in British date format
set dateformat dmy
go
use tempdb
go
create table foo( bar varchar( 30 ) not null )
go
insert into foo( bar ) values ( 'fishy' )
insert into foo( bar ) values ( '19/07/2007' )
go
-- this works fine in all versions - only valid dates are passed to the convert function
select
convert( smalldatetime, bar, 103 ) as bardate
from
foo
where
bar like '__/__/____'
go
-- this works on SQL 2000, but fails on SQL 2005 SP2 (I've not tried other SPs of SQL 2005):
-- Msg 295, Level 16, State 3, Line 2
-- Conversion failed when converting character string to smalldatetime data type.
--
-- I believe the query is rewritten as if the derived table query contained
-- "and convert( smalldatetime, bar, 103 ) < getdate()"
-- which would expose the convert to the invalid data
select
*
from
(
select
convert( smalldatetime, bar, 103 ) as bardate
from
foo
where
bar like '__/__/____'
) as derived
where
bardate < getdate()
go
-- Workaround:
-- Use a case statement to protect the convert operator from the invalid data
select
*
from
(
select
case when bar like '__/__/____' then
convert( smalldatetime, bar, 103 )
else
null
end as bardate
from
foo
where
bar like '__/__/____'
) as derived
where
bardate < getdate()
go
drop table foo
go
The workaround I discovered is simple but ugly. I invite your comments...
how to declare multiple derived columns in SSIS Derived Column Task in one attempt.as i have around 150 columns coming from Flat file. I had created the required Expression in Excel and now i want add those in derived column task but its allowing only 1 expression at a time.
I am using CROSS APPLY instead of UNPIVOT to unpivot > one column. I am wondering if I can dynamically replace column names based on different tables? The example code that I have working is based on the "Allergy" table. I have thirty more specialty tables to go. I'll show the working code first, then an example of another table's columns to show differences:
select [uplift specialty], [member po],[practice unit name], [final nomination status] ,[final uplift status], [final rank], [final uplift percentage] ,practiceID=row_number() over (partition by [practice unit name] order by Metricname) ,metricname,Metricvalue, metricpercentilerank
[code]....
Rheumatology Table:The columns that vary start with "GDR" and [GDR Percentile Rank] so I'm just showing those:
I am looking for the best way in SSIS to do the following. I have an SQL table that for each row in the table I want to take an element from the table do a lookup in a Teredata Table, return information from the teredata source. Use that returned data to do some calculations and create a derived column from my calculations and place the data into the same SQL table that I am parsing through.