Move data from SQL results to existing table - sql

I'm a little bit stuck. I have a database table with the following columns:
Table Name: Data
*Value
*DateTime
*WeekNumber
*ItemId
*Name
I have created the following scripts from which I'd like to place the results into the above table.
SELECT D.*, M.Name
FROM
(SELECT SUM (Data) AS [Value],
(SELECT CONVERT(Date,DATEADD(week,-1,GETDATE()))) [DateTimeValue], DatePart (Week,TimestampUTC) [WeekNumber], MT.MeterId [MeterID]
FROM DataLog.dl
JOIN MeterTags mt ON dl.MeterTagId = mt.MeterTagId
GROUP BY DatePart (Week,TimestampUTC, dl.MeterTagId, MeterId)
AS D
INNER JOIN Meters m
ON D.MeterId = M.MeterId
ORDER BY MeterId DESC
I'm hoping to drop the results from the above query into the corresponding columns in the db table along with creating a new one for MeterID:
Value = Value
DateTime = DateTimeValue
WeekNumber = WeekNumber
MeterID = ***Need to create a new column*****
Name = Name
I hope this makes sense as I'm pretty inexperienced with SQL and a struggling to get the last pieces put together. Any help you can give would be greatly appreciated.
Thanks.

you can use the standard SQL INSERT syntax
INSERT INTO table2
SELECT * FROM table1;
what i don't understand is what do you mean by
MeterID = Need to create a new column**
for more info look
http://www.w3schools.com/sql/sql_insert_into_select.asp and
http://msdn.microsoft.com/en-us/library/ms188263(v=sql.105).aspx

Modify your table and add new column for MeterId.
Insert into [Data]
SELECT D.[Value], D.DateTimeValue,D.WeekNumber,MT.MeterId,M.Name
FROM
(SELECT SUM (Data) AS [Value],
(SELECT CONVERT(Date,DATEADD(week,-1,GETDATE()))) [DateTimeValue], DatePart (Week,TimestampUTC) [WeekNumber], MT.MeterId [MeterID]
FROM DataLog.dl
JOIN MeterTags mt ON dl.MeterTagId = mt.MeterTagId
GROUP BY DatePart (Week,TimestampUTC, dl.MeterTagId, MeterId)
AS D
INNER JOIN Meters m
ON D.MeterId = M.MeterId
ORDER BY MeterId DESC

Related

Rewrite query without using temp table

I have a query that is using a temp table to insert some data then another select from to extract distinct results. That query by it self was fine but now with entity-framework it is causing all kinds of unexpected errors at the wrong time.
Is there any way I can rewrite the query not to use a temp table? When this is converted into a stored procedure and in entity framework the result set is of type int which throws an error:
Could not find an implementation of the query pattern Select not found.
Here is the query
Drop Table IF EXISTS #Temp
SELECT
a.ReceiverID,
a.AntennaID,
a.AntennaName into #Temp
FROM RFIDReceiverAntenna a
full join Station b ON (a.ReceiverID = b.ReceiverID) and (a.AntennaID = b.AntennaID)
where (a.ReceiverID is NULL or b.ReceiverID is NULL)
and (a.AntennaID IS NULL or b.antennaID is NULL)
select distinct r.ReceiverID, r.ReceiverName, r.receiverdescription
from RFIDReceiver r
inner join #Temp t on r.ReceiverID = t.ReceiverID;
No need for anything fancy, you can just replace the reference to #temp with an inner sub-query containing the query that generates #temp e.g.
select distinct r.ReceiverID, r.ReceiverName, r.receiverdescription
from RFIDReceiver r
inner join (
select
a.ReceiverID,
a.AntennaID,
a.AntennaName
from RFIDReceiverAntenna a
full join Station b ON (a.ReceiverID = b.ReceiverID) and (a.AntennaID = b.AntennaID)
where (a.ReceiverID is NULL or b.ReceiverID is NULL)
and (a.AntennaID IS NULL or b.antennaID is NULL)
) t on r.ReceiverID = t.ReceiverID;
PS: I haven't made any effort to improve the query overall like Gordon has but do consider his suggestions.
First, a full join makes no sense in the first query. You are selecting only columns from the first table, so you need that.
Second, you can use a CTE.
Third, you should be able to get rid of the SELECT DISTINCT by using an EXISTS condition.
I would suggest:
WITH ra AS (
SELECT ra.*
FROM RFIDReceiverAntenna ra
Station s
ON s.ReceiverID = ra.ReceiverID AND
s.AntennaID = ra.AntennaID)
WHERE s.ReceiverID is NULL
)
SELECT r.ReceiverID, r.ReceiverName, r.receiverdescription
FROM RFIDReceiver r
WHERE EXISTS (SELECT 1
FROM ra
WHERE r.ReceiverID = ra.ReceiverID
);
You can use CTE instead of the temp table:
WITH
CTE
AS
(
SELECT
a.ReceiverID,
a.AntennaID,
a.AntennaName
FROM
RFIDReceiverAntenna a
full join Station b
ON (a.ReceiverID = b.ReceiverID)
and (a.AntennaID = b.AntennaID)
where
(a.ReceiverID is NULL or b.ReceiverID is NULL)
and (a.AntennaID IS NULL or b.antennaID is NULL)
)
select distinct
r.ReceiverID, r.ReceiverName, r.receiverdescription
from
RFIDReceiver r
inner join CTE t on r.ReceiverID = t.ReceiverID
;
This query will return the same results as your original query with the temp table, but its performance may be quite different; not necessarily slower, it can be faster. Just something that you should be aware about.

SQL Inner Join and nearest row to date

I dont't get it. I changed some of the code. In the WPLEVENT Table are a lot of Events per person. In the Persab-Table are the Persons with their History. Now I need the from the Persab Table just that row wich matches the persab.gltab Date nearest to the WPLEVENT.vdat Date. So all rows from the WPLEVENT, but just the one matching row from the PERSAB-Table.
SELECT
persab.name,
persab.vorname,
vdat,
eventstart,
persab.rc1,
persab.rc2
FROM wplevent
INNER JOIN
persab ON WPLEVENT.PersID = persab.PRIMKEY
INNER JOIN
(SELECT TOP 1 persab.rc1
FROM PERSAB
WHERE persab.gltab <= getdate() --/ Should be wplevent.vdat instead of getdate()
) NewTable ON wplevent.persid = persab.primkey
WHERE
persid ='100458'
ORDER BY vdat DESC
Need to use the MAX() function with the proper syntax by supplying an expression like MAX(persab.rc1). Also need to use GROUP BY for the second column rc2 in the subquery (although it looks like you do not need it). Finally you are missing the ON clause for the final INNER JOIN. I can update the answer to fix the query if you provide that information.
SELECT
Z1PERS.NAME
, Z1PERS.VORNAME
, WPLEVENT.VDat
, WPLEVENT.EventStart
, WPLEVENT.EventStop
, WPLEVENT.PEPGROUP
, Z1SGRP.TXXT
, PERSAB.GLTAB
, Z1PERS.PRIMKEY AS Expr1
, PERSAB.PRIMKEY
FROM
Z1PERS
INNER JOIN
WPLEVENT ON Z1PERS.PRIMKEY = WPLEVENT.PersID
INNER JOIN
Z1SGRP ON WPLEVENT.PEPGROUP = Z1SGRP.GRUPPE
INNER JOIN
(
SELECT MAX(Persab.rc1) --Fixed MAX expression
, persab.rc2
FROM
persab
GROUP BY
persab.rc2 --Need to group on rc2 if you want that column in the query otherwise remove this AND the rc2 column from select list
WHERE
WPLEVENT.PersID = PERSAB.PRIMKEY
AND WPLEVENT.VDat <= PERSAB.GLTAB
) --Missing ON clause for the INNER JOIN here
WHERE z1pers.vorname = 'henning'

SQL - Must declare the scalar variable error

I can't seem to figure out what is wrong with my SQL code. It says I need to declare the scalar variable #tempMile2, but it is a declared table.
INSERT INTO #tempMile (UserFullName, USERs_ID, timecard_date, timecard_createddate)
SELECT UserFullName, USERs_ID, timecard_date, timecard_createddate
FROM v_tblTimeCard
WHERE convert(date, TimeCard_CreatedDate) = dateadd(day,-1, cast(getdate() as date))
group by
userfullname,
USERs_ID,
timecard_date,
TimeCard_CreatedDate
DECLARE #tempMile2 table (USERs_ID int, timecard_date date)
INSERT INTO #tempMile2 (USERs_ID, timecard_date)
SELECT USERs_ID, timecard_date --add count logic here --timecard entries 1 for day
FROM #tempMile
group by USERs_ID, timecard_date
select * from dbo.tblMileage left join
#tempMile2 on tblMileage.Users_ID = #tempMile2.USERs_ID AND tblMileage.DateOfService = #tempMile2.timecard_date
where #tempMile2.TimeCard_Date IS NOT NULL
It is only in the last select statement where the #tempMile2 is asking to be declared.
Any thoughts?
You cannot use a table variable to qualify a column name. The table alias cannot start with #. So, try this:
select *
from dbo.tblMileage m left join
#tempMile2 tm
on m.Users_ID = tm.USERs_ID and m.DateOfService = tm.timecard_date
where tm.TimeCard_Date IS NOT NULL;
Of course, your comparison in the where clause implies that the join is an inner join, not an outer join, but I didn't make that change.

SQL Group By Clause and Empty Entries

I have a SQL Server 2005 query that I'm trying to assemble right now but I am having some difficulties.
I have a group by clause based on 5 columns: Project, Area, Name, User, Engineer.
Engineer is coming from another table and is a one to many relationship
WITH TempCTE
AS (
SELECT htce.HardwareProjectID AS ProjectId
,area.AreaId AS Area
,hs.NAME AS 'Status'
,COUNT(*) AS Amount
,MAX(htce.DateEdited) AS DateModified
,UserEditing AS LastModifiedName
,Engineer
,ROW_NUMBER() OVER (
PARTITION BY htce.HardwareProjectID
,area.AreaId
,hs.NAME
,htce.UserEditing ORDER BY htce.HardwareProjectID
,Engineer DESC
) AS row
FROM HardwareTestCase_Execution AS htce
INNER JOIN HardwareTestCase AS htc ON htce.HardwareTestCaseID = htc.HardwareTestCaseID
INNER JOIN HardwareTestGroup AS htg ON htc.HardwareTestGroupID = htg.HardwareTestGroupId
INNER JOIN Block AS b ON b.BlockId = htg.BlockId
INNER JOIN Area ON b.AreaId = Area.AreaId
INNER JOIN HardwareStatus AS hs ON htce.HardwareStatusID = hs.HardwareStatusId
INNER JOIN j_Project_Testcase AS jptc ON htce.HardwareProjectID = jptc.HardwareProjectId AND htce.HardwareTestCaseID = jptc.TestcaseId
WHERE (htce.DateEdited > #LastDateModified)
GROUP BY htce.HardwareProjectID
,area.AreaId
,hs.NAME
,htce.UserEditing
,jptc.Engineer
)
The gist of what I want is to be able to deal with empty Engineer columns. I don't want this column to have a blank second entry (where row=2).
What I want to do:
Group the items with "row" value of 1 & 2 together.
Select the Engineer that isn't empty.
Do not deselect engineers where there is not a matching row=2.
I've tried a series of joins to try and make things work. No luck so far.
Use j_Project_Testcase PIVOT( MAX(Engineer) for Row in ( [1], [2] ) then select ISNULL( [1],[2]) to select the Engineer value
I can give you a more robust example if you set up a SQL fiddle
Try reading this: PIVOT and UNPIVOT

linq to entities - try this one!

Im converting to linq to entities and I am finding problems attempting to convert the stored procs I have created as an overview of data.
How do I convert this sql statement to linq to entities:
I have a venue table with a child venuerooms table. With the last part I want to get the largest capacity for that venue across all rooms and roomtypes.
This is currently working in sql server 2005
Any help would be greately appreciated
ALTER proc [dbo].[sp_getVenueOverview]
(#venue varchar(100)) as
SELECT (Select accomrooms
from tblvenue
where venueid=(select venueid from tblvenue where urlfriendly = #venue))
as accomrooms,
(Select count(*)
from tblvenueroom
where venueid=(select venueid from tblvenue where urlfriendly = #venue))
as roomcount,
(Select Max(dbo.Greatest(theatrestyle,classroom,boardroom,ushape,banquet,cocktail))
from tblvenueroom
where venueid=(select venueid from tblvenue where urlfriendly = #venue))
as largest
you might want to refactor the query first, here is my try:
SELECT
v.accomrooms,r.roomcount,r.largest
FROM tblvenue v
LEFT OUTER JOIN (SELECT
v.venueid
,COUNT(*) AS roomcount
,Max(dbo.Greatest(r.theatrestyle,r.classroom,r.boardroom,r.ushape,r.banquet,r.cocktail) AS largest --dbo.Greatest() kills performance!
FROM tblvenue v
INNER JOIN tblvenueroom r ON v.venueid=r.venueid
WHERE v.urlfriendly = #venue
GROUP BY v.venueid
) dt ON v.venueid=dt.venueid
WHERE v.urlfriendly = #venue