SQL Server Insert Into Pivoted View - sql-server

Let's say I have a table testpivot that looks like this, with district and metric a unique key:
id
district
metric
value
1
a
work
40
2
a
hours
80
3
b
work
50
4
b
hours
85
I create a view:
CREATE VIEW vpivot
AS
SELECT *
FROM(
SELECT district, metric, value
FROM testpivot
)t
PIVOT(SUM(value) for metric IN(work,hours)) as p
So querying from the view looks like this:
district
work
hours
a
40
80
b
50
85
Is there a way to make an insert query like this work:
INSERT INTO vpivot SELECT 'c',20,80

Select * from vpivot
UNION
SELECT 'c',20,80

Related

How can an SQL query return data from these tables?

I have TrsViewPay view with this sample data:
id DocTypeRef TrsDocPayItemref
---------------------------------
1 10 16
2 20 17
3 30 18
4 40 1
First I don't want to show record with DocTypeRef 40.
Then I don't want to show the records where the id is equal with that record's TrsDocPayItemref.
So I want to show this result (without record 1 and 4)
id DocTypeRef TrsDocPayItemref
---------------------------------
2 20 17
3 30 18
Ravi's answer is close, but I think this one will be better:
SELECT Id, DocTypeRef, TrsDocPayItemref
FROM TrsViewPay
WHERE DocTypeRef <> 40
AND Id <> (SELECT TrsDocPayItemref FROM TrsViewPay WHERE DocTypeRef = 40)
You can go for inner queries or sub queries. You can first Select the value of
DocTypeRef and then compare it with id. use first point as inner query. After that you can retrieve data using the result of first query.
You can try this:
SELECT *
FROM TrsViewPay
WHERE DocTypeRef!=40
AND NOT TrsDocPayItemref IN (SELECT id FROM TrsViewPay )

FETCH specific number of primary key rows

I have an SQL SELECT that left-joins several tables together, which results in an output with redundant data.
Example query:
SELECT
A.ID, B.ID
FROM A
LEFT JOIN B ON B.ParentID=A.ID
FETCH NEXT 4 ROWS ONLY
Example output:
A.ID B.ID
1 10
1 20
2 30
2 40
My problem is that I want to limit the number of rows from the A table, not from the actual output. In short, I would like to have an output like this when I ask for 4 rows:
A.ID B.ID
1 10
1 20
2 30
2 40
3 50
3 60
4 70
4 80
Any advice?
UPDATE:
Here is a fiddle that could help explaining the problem:
Fiddle
i have applied query on actual data, use sub query to get top 4 result.
declare #temp table
(aId int, bId int)
insert into #temp
values
(1,10),
(1,20),
(2,30),
(2,40),
(3,50),
(3,60),
(4,70),
(4,80),
(5,90),
(6,100)
select * from #temp
where aId in
(select distinct top 4 aId from #temp where aId > 1)

Pivot query without knowing the number of columns needed

I have a query that returns the following data.
ProductCode DealRef
1120 23
1120 76
1130 24
Is there a way that if a product code has more than one Deal ref then it will put this into a new column? So the current result would look something like;
ProductCode Deal1 Deal2
1120 23 76
1130 24
If this is not possible then I have an idea that could work. I would do a count on the DealRef column to find out many columns i would need to pivot to. I would then need to add another column to my initial query which will be able to add an id to each row displaying something similar to the below which I'm unsure how to do.
ProductCode DealRef id
1120 23 1
1120 76 2
1130 24 1
You cannot get the fitting number of columns, but you can get as many columns as you expect to be the maximum, most of them beeing NULL:
Paste this into an empty query window and execute. Adapt to your needs
DECLARE #tbl TABLE(ProductCode INT, DealRef INT);
INSERT INTO #tbl VALUES
(1120,23)
,(1120,76)
,(1130,24);
SELECT p.*
FROM
(
SELECT 'deal' + CAST(ROW_NUMBER() OVER(PARTITION BY tbl.ProductCode ORDER BY tbl.ProductCode) AS VARCHAR(10)) AS ColumnName
,tbl.ProductCode
,tbl.DealRef
FROM #tbl AS tbl
) AS x
PIVOT
(
MIN(DealRef) FOR ColumnName IN(deal1,deal2,deal3,deal4 /*Add as many Col-names as you could maximum need*/)
) AS p
Result is
ProductCode deal1 deal2 deal3 deal4
1120 23 76 NULL NULL
1130 24 NULL NULL NULL

Removing Duplicates of two columns in a query

I have a select * query which gives lots of row and lots of columns of results. I have an issue with duplicates of one column A when given the same value of another column B that I would like to only include one of.
Basically I have a column that tells me the "name" of object and another that tells me the "number". Sometimes I have an object "name" with more than one entry for a given object "number". I only want distinct "numbers" within a "name" but I want the query to give the entire table when this is true and not just these two columns.
Name Number ColumnC ColumnD
Bob 1 93 12
Bob 2 432 546
Bob 3 443 76
This example above is fine
Name Number ColumnC ColumnD
Bob 1 93 12
Bob 2 432 546
Bill 1 443 76
Bill 2 54 1856
This example above is fine
Name Number ColumnC ColumnD
Bob 1 93 12
Bob 2 432 546
Bob 2 209 17
This example above is not fine, I only want one of the Bob 2's.
Try it if you are using SQL 2005 or above:
With ranked_records AS
(
select *,
ROW_NUMBER() OVER(Partition By name, number Order By name) [ranked]
from MyTable
)
select * from ranked_records
where ranked = 1
If you just want the Name and number, then
SELECT DISTINCT Name, Number FROM Table1
If you want to know how many of each there are, then
SELECT Name, Number, COUNT(*) FROM Table1 GROUP BY Name, Number
By using a Common Table Expression (CTE) and the ROW_NUMBER OVER PARTION syntax as follows:
WITH
CTE AS
(
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY Name, Number ORDER BY Name, Number) AS R
FROM
dbo.ATable
)
SELECT
*
FROM
CTE
WHERE
R = 1
WITH
CTE AS
(
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY Plant, BatchNumber ORDER BY Plant, BatchNumber) AS R
FROM dbo.StatisticalReports WHERE dbo.StatisticalReports. \!"FermBatchStartTime\!" >= DATEADD(d,-90, getdate())
)
SELECT
*
FROM
CTE
WHERE
R = 1
ORDER BY dbo.StatisticalReports.Plant, dbo.StatisticalReports.FermBatchStartTime

Selecting between more than 2 rows from DB

I know that I can select elements between two rows like:
SELECT * FROM table WHERE id BETWEEN 20 AND 30
Can someone tell me how can I select using one query between 4 rows like between 20 and 30 and between 40 and 50?
SELECT * FROM table WHERE id BETWEEN 20 AND 30 OR id BETWEEN 40 and 50

Resources