Monday, March 26, 2012
Query with MAX Date
The name of a product can change with time. These changes are stored in a
table with 3 columns: Product_id, Date and ProductName with Product_id and
Date forming the Primary Key.
I want to run a query that returns the product_id and each product's latest
name. For the life of me, I can't get my head rould what such a query would
look like. I can get a query that gives me just the product_id and the Max
of Date with a group by on the Product_id but when I introduce the
ProductName, it returns ALL names.
I have a gut feeling that there may be a subquery involved, or am I barking
up the wrong tree?
Any help much appreciated.
PeteYou can either use a subquery:
SELECT Product_id, ProductName
FROM Your_table t1
WHERE Date = (SELECT MAX(Date) FROM Your_table t2 WHERE t1.Product_id =
t2.Product_id)
or a derived table:
SELECT t1.Product_id, t1.ProductName
FROM Your_table t1
INNER JOIN
(SELECT Product_id, MAX(Date) AS max_date
FROM Your_table
GROUP BY Product_id) t2
ON t1.Product_id = t2.Product_id
AND t1.Date = t2.max_date
Jacco Schalkwijk
SQL Server MVP
"Italian Pete" <ItalianPete@.discussions.microsoft.com> wrote in message
news:4847B525-302C-4354-99EE-8165C56B60D9@.microsoft.com...
>I have the following situation:
> The name of a product can change with time. These changes are stored in a
> table with 3 columns: Product_id, Date and ProductName with Product_id and
> Date forming the Primary Key.
> I want to run a query that returns the product_id and each product's
> latest
> name. For the life of me, I can't get my head rould what such a query
> would
> look like. I can get a query that gives me just the product_id and the
> Max
> of Date with a group by on the Product_id but when I introduce the
> ProductName, it returns ALL names.
> I have a gut feeling that there may be a subquery involved, or am I
> barking
> up the wrong tree?
> Any help much appreciated.
> Pete|||First, please change your column name 'Date' to something more meaningful
and something that doesn't use a reserved word. Also, you should be
consistent in your column naming. Why does Product_id have an underscore,
but ProductName not? Finally, in the future, please post DDL, sample data,
and desired results. See http://www.aspfaq.com/5006
In the meantime, you can try this:
SELECT o.Product_id, i.MaxDate, o.ProductName
FROM Products o
INNER JOIN
(
SELECT Product_id, MaxDate = MAX([Date])
FROM Products
GROUP BY Product_id
) i
ON o.Product_id = i.Product_id
AND o.[Date] = i.MaxDate
http://www.aspfaq.com/
(Reverse address to reply.)
"Italian Pete" <ItalianPete@.discussions.microsoft.com> wrote in message
news:4847B525-302C-4354-99EE-8165C56B60D9@.microsoft.com...
> I have the following situation:
> The name of a product can change with time. These changes are stored in a
> table with 3 columns: Product_id, Date and ProductName with Product_id and
> Date forming the Primary Key.
> I want to run a query that returns the product_id and each product's
latest
> name. For the life of me, I can't get my head rould what such a query
would
> look like. I can get a query that gives me just the product_id and the
Max
> of Date with a group by on the Product_id but when I introduce the
> ProductName, it returns ALL names.
> I have a gut feeling that there may be a subquery involved, or am I
barking
> up the wrong tree?
> Any help much appreciated.
> Pete|||Here is a solution based on guesswork:
SELECT t1.product_id, t1.product_name
FROM tbl t1
WHERE ( SELECT MAX( t2.dtcol )
FROM tbl t2
WHERE t2.product_id = t1.product_id ) = t1.dtcol ;
If this is not what you are looking for, refer to www.aspfaq.com/5006 and
provide required information.
Anith
Friday, March 23, 2012
Query value in between two columns
I am new to Sql and I want to know if a given value lets say its 225
is within ranges defined in the table.
I have a table TblControl. Data type of both field is int.
StartRange End Range
0 100
200 300
500 600
900 950
(Sql server 2000 on window 2000)
Thanks
-MaxOn 26 Aug 2004 12:13:48 -0700, Max wrote:
>Hi All,
>I am new to Sql and I want to know if a given value lets say its 225
>is within ranges defined in the table.
>I have a table TblControl. Data type of both field is int.
>StartRange End Range
>0 100
>200 300
>500 600
>900 950
>(Sql server 2000 on window 2000)
>Thanks
>-Max
Hi Max,
You can test this with BETWEEN. Example:
SELECT StartRange, EndRange
FROM Control
WHERE 225 BETWEEN StartRange AND EndRange
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Thanks Hugo,
It solved my problem.
-Maxsql
Query using dynamic column names
I have a table DATA with following 20 columns.
COL1, COL2, COL3, COL4,..... COL20
Another table TEMPLATE has one column COLNAME. The table contains 5 rows with the data COL2, COL5, COL6, COL9, COL12 in the column COLNAME.
Can someone help me to build sql statement to select data from DATA table for only columns listed in the TEMPLATE table. I want to do this using only one select statement. (I know how to do this with stored procedure but thats not what I want)
Also it is possible that row in TEMPLATE table may change.
Hope to get some positive replies.
Reagrds,
HK
If all the columns are of compatible types then you can do it like this:
CREATE TABLE Template (colname VARCHAR(10) PRIMARY KEY, ordinal_pos INTEGER
NOT NULL UNIQUE)
INSERT INTO Template VALUES ('COL1',1)
INSERT INTO Template VALUES ('COL2',2)
INSERT INTO Template VALUES ('COL3',3)
SELECT MIN(CASE
WHEN T.ordinal_pos = 1 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 1 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 1 AND T.colname='col3' THEN col3
/* .. etc */
END),
MIN(CASE
WHEN T.ordinal_pos = 2 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 2 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 2 AND T.colname='col3' THEN col3
END),
MIN(CASE
WHEN T.ordinal_pos = 3 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 3 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 3 AND T.colname='col3' THEN col3
END),
...
FROM Data AS D
CROSS JOIN Template AS T
GROUP BY D.col1, D.col2, D.col3, ... other cols
Otherwise use IF statements or dynamic SQL. You could also consider building
the SELECT statement client-side or retrieve all the columns but display
only the required ones to the user.
David Portas
SQL Server MVP
|||Thanks for your help David. But this will not work for me. The example I gave was to explain my problem. But in reality, I will not know all column names in the DATA table, only TEMPLATE table is the guide which has list of fields to select from DATA tabl
e.
Regards,
HK
"David Portas" wrote:
> If all the columns are of compatible types then you can do it like this:
> CREATE TABLE Template (colname VARCHAR(10) PRIMARY KEY, ordinal_pos INTEGER
> NOT NULL UNIQUE)
> INSERT INTO Template VALUES ('COL1',1)
> INSERT INTO Template VALUES ('COL2',2)
> INSERT INTO Template VALUES ('COL3',3)
> SELECT MIN(CASE
> WHEN T.ordinal_pos = 1 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 1 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 1 AND T.colname='col3' THEN col3
> /* .. etc */
> END),
> MIN(CASE
> WHEN T.ordinal_pos = 2 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 2 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 2 AND T.colname='col3' THEN col3
> END),
> MIN(CASE
> WHEN T.ordinal_pos = 3 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 3 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 3 AND T.colname='col3' THEN col3
> END),
> ...
> FROM Data AS D
> CROSS JOIN Template AS T
> GROUP BY D.col1, D.col2, D.col3, ... other cols
> Otherwise use IF statements or dynamic SQL. You could also consider building
> the SELECT statement client-side or retrieve all the columns but display
> only the required ones to the user.
> --
> David Portas
> SQL Server MVP
> --
>
>
Query using dynamic column names
I have a table DATA with following 20 columns.
COL1, COL2, COL3, COL4,..... COL20
Another table TEMPLATE has one column COLNAME. The table contains 5 rows wi
th the data COL2, COL5, COL6, COL9, COL12 in the column COLNAME.
Can someone help me to build sql statement to select data from DATA table fo
r only columns listed in the TEMPLATE table. I want to do this using only on
e select statement. (I know how to do this with stored procedure but thats n
ot what I want)
Also it is possible that row in TEMPLATE table may change.
Hope to get some positive replies.
Reagrds,
HKIf all the columns are of compatible types then you can do it like this:
CREATE TABLE Template (colname VARCHAR(10) PRIMARY KEY, ordinal_pos INTEGER
NOT NULL UNIQUE)
INSERT INTO Template VALUES ('COL1',1)
INSERT INTO Template VALUES ('COL2',2)
INSERT INTO Template VALUES ('COL3',3)
SELECT MIN(CASE
WHEN T.ordinal_pos = 1 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 1 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 1 AND T.colname='col3' THEN col3
/* .. etc */
END),
MIN(CASE
WHEN T.ordinal_pos = 2 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 2 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 2 AND T.colname='col3' THEN col3
END),
MIN(CASE
WHEN T.ordinal_pos = 3 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 3 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 3 AND T.colname='col3' THEN col3
END),
..
FROM Data AS D
CROSS JOIN Template AS T
GROUP BY D.col1, D.col2, D.col3, ... other cols
Otherwise use IF statements or dynamic SQL. You could also consider building
the SELECT statement client-side or retrieve all the columns but display
only the required ones to the user.
David Portas
SQL Server MVP
--|||Thanks for your help David. But this will not work for me. The example I gav
e was to explain my problem. But in reality, I will not know all column name
s in the DATA table, only TEMPLATE table is the guide which has list of fiel
ds to select from DATA tabl
e.
Regards,
HK
"David Portas" wrote:
> If all the columns are of compatible types then you can do it like this:
> CREATE TABLE Template (colname VARCHAR(10) PRIMARY KEY, ordinal_pos INTEGE
R
> NOT NULL UNIQUE)
> INSERT INTO Template VALUES ('COL1',1)
> INSERT INTO Template VALUES ('COL2',2)
> INSERT INTO Template VALUES ('COL3',3)
> SELECT MIN(CASE
> WHEN T.ordinal_pos = 1 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 1 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 1 AND T.colname='col3' THEN col3
> /* .. etc */
> END),
> MIN(CASE
> WHEN T.ordinal_pos = 2 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 2 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 2 AND T.colname='col3' THEN col3
> END),
> MIN(CASE
> WHEN T.ordinal_pos = 3 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 3 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 3 AND T.colname='col3' THEN col3
> END),
> ...
> FROM Data AS D
> CROSS JOIN Template AS T
> GROUP BY D.col1, D.col2, D.col3, ... other cols
> Otherwise use IF statements or dynamic SQL. You could also consider buildi
ng
> the SELECT statement client-side or retrieve all the columns but display
> only the required ones to the user.
> --
> David Portas
> SQL Server MVP
> --
>
>
Query using dynamic column names
I have a table DATA with following 20 columns.
COL1, COL2, COL3, COL4,..... COL20
Another table TEMPLATE has one column COLNAME. The table contains 5 rows with the data COL2, COL5, COL6, COL9, COL12 in the column COLNAME.
Can someone help me to build sql statement to select data from DATA table for only columns listed in the TEMPLATE table. I want to do this using only one select statement. (I know how to do this with stored procedure but thats not what I want)
Also it is possible that row in TEMPLATE table may change.
Hope to get some positive replies.
Reagrds,
HKIf all the columns are of compatible types then you can do it like this:
CREATE TABLE Template (colname VARCHAR(10) PRIMARY KEY, ordinal_pos INTEGER
NOT NULL UNIQUE)
INSERT INTO Template VALUES ('COL1',1)
INSERT INTO Template VALUES ('COL2',2)
INSERT INTO Template VALUES ('COL3',3)
SELECT MIN(CASE
WHEN T.ordinal_pos = 1 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 1 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 1 AND T.colname='col3' THEN col3
/* .. etc */
END),
MIN(CASE
WHEN T.ordinal_pos = 2 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 2 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 2 AND T.colname='col3' THEN col3
END),
MIN(CASE
WHEN T.ordinal_pos = 3 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 3 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 3 AND T.colname='col3' THEN col3
END),
...
FROM Data AS D
CROSS JOIN Template AS T
GROUP BY D.col1, D.col2, D.col3, ... other cols
Otherwise use IF statements or dynamic SQL. You could also consider building
the SELECT statement client-side or retrieve all the columns but display
only the required ones to the user.
--
David Portas
SQL Server MVP
--|||Thanks for your help David. But this will not work for me. The example I gave was to explain my problem. But in reality, I will not know all column names in the DATA table, only TEMPLATE table is the guide which has list of fields to select from DATA table.
Regards,
HK
"David Portas" wrote:
> If all the columns are of compatible types then you can do it like this:
> CREATE TABLE Template (colname VARCHAR(10) PRIMARY KEY, ordinal_pos INTEGER
> NOT NULL UNIQUE)
> INSERT INTO Template VALUES ('COL1',1)
> INSERT INTO Template VALUES ('COL2',2)
> INSERT INTO Template VALUES ('COL3',3)
> SELECT MIN(CASE
> WHEN T.ordinal_pos = 1 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 1 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 1 AND T.colname='col3' THEN col3
> /* .. etc */
> END),
> MIN(CASE
> WHEN T.ordinal_pos = 2 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 2 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 2 AND T.colname='col3' THEN col3
> END),
> MIN(CASE
> WHEN T.ordinal_pos = 3 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 3 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 3 AND T.colname='col3' THEN col3
> END),
> ...
> FROM Data AS D
> CROSS JOIN Template AS T
> GROUP BY D.col1, D.col2, D.col3, ... other cols
> Otherwise use IF statements or dynamic SQL. You could also consider building
> the SELECT statement client-side or retrieve all the columns but display
> only the required ones to the user.
> --
> David Portas
> SQL Server MVP
> --
>
>
Wednesday, March 21, 2012
query to xml question
I have a table that contains 3 columns SiteID, Results and date. the table has 4 rows. I want to query the table and end up with 1 row that combines all the field into in the Results Column.
so in table form it looks like
627 test 3/3/7
627 bob 3/3/7
627 tom 3/9/7
627 rob 3/8/7
I want the resulting query to bring back one row:
test,bob,tom,rob
the following query will do 90% of what I want,
SELECT test +','
FROM #temp1
FORXMLPATH('')
BUT I cannot figure out how to provide a column name for the query result. instead I appear to get a guid of XML_F52E2B61-18A1-11d1-B105-00805F49916B
Q - is there a way to name the column, or is there a different way to create this query result without using XML?
I am us
Jim:
The best way is to make your select statement into a "derived table" or a correlated subquery; For example:
|||create table #temp1
( SiteID integer,
Results varchar(10),
date datetime
)
insert into #temp1 values (627, 'billy joe', '3/3/7')
insert into #temp1 values (627, 'bob', '3/3/7')
insert into #temp1 values (627, 'tom', '3/9/7')
insert into #temp1 values (627, 'rob', '3/8/7')select distinct
siteId,
replace(replace(
( select replace (x.results, ' ', '~') as [data()]
from #temp1 x
where x.siteId = x.siteId
order by date
for xml path ('')
), ' ', ','), '~', ' ') as dataLabel
from #temp1 a-- siteId dataLabel
-- --
-- 627 billy joe,bob,rob,tomgo
drop table #temp1
go
selectcast((SELECT test +','FROM #temp1 FORXMLPATH(''))asvarchar(max))as YourName
|||I think I like Konstantin's better.|||Thanks to both of you for the quick reply, they both work, but think I will use Konstantin's
|||Actually I now have a different problem:
I am using
select siteid, Cast((SELECT Anomalies+ ',' FROM #temp1 FOR XML PATH('')) as varchar(max) ) as Anomaly from #temp1
this does work, sort of.... But it creates the result for all records in the table. I need it to create a seperate record for each siteid, otherwise all the resulting data is the same for all siteids?
any ideas?
|||Just add filter to subquery:select siteid, Cast((SELECT Anomalies+ ',' FROM #temp1 where siteid=t.siteid FOR XML PATH('')) as varchar(max) ) as Anomaly from #temp1 t
sql
Query to View with Many Columns
Hi All,
I have a simple question. If I have a view that query from joined multiple tables and return a lot of columns (more than 100). If I run a simple query just return several columns (e.g. 4-5 columns), will SQL Server query all columns first from all joined table? or can SQL Server query only necessary column from related table?
Does anyone have idea how to join table that can reflect both left and right join?
Table A Table B
Column1 Column2 Column3 Column4 Column1 Column2 Column 3 Column5
A Jan 5 xxx A Jan 1 yyy
B Feb 3 C Mar 4
B Mar 4 C Apr 3
C Apr 2 D May 2
E Mar 1
Result Table
Column1 Column2 Column3 Column4 Column 5
A Jan 6 (= 5+1) xxx yyyy
B Feb 3
B Mar 4
C Mar 4
C Apr 5 (= 2+3)
D May 2
E Mar 1
So the result table is a join on column1 and column2 (both are primary key), with column3 is a sum aggregate. Table A has additional column4 and Table B has additional column5, so quite difficult to union (In fact, there are a lot of column differences between table).
Thanks for the help.
The VIEW will first create a virtual table containing ALL of the columns, and then you will get a resultset of just the columns requested.
That could be very inefficient. Most likely, it would be better to query against the underlaying table for just the columns required. Or create a separate VIEW for this purpose.
|||Thanks for the answer .
The problem is this query will be executed by Report Builder, so all of those columns will be needed as user might select any combination to include in the report, so it's quite difficult to provide only certain column by creating another view. I already try to separate the View into multiple entity in Report Builder, but when it comes to the aggregate, some of the calculation is calculated wrongly in the Report Builder, and some complexity with multiple currency/exchange rate araise, that force me to add more column inside the view .
Any idea or suggestion for my situation? Thanks
|||You haven't provided enough detail for anyone to offer cogent suggestions.
However, one thing comes to mind. You might be able to use a Stored Procedure that Creates a custom VIEW (from input parameters), and then returns the resultset from that VIEW.
query to split a database column ?
How can i write a query to split a database column and shows 2 new columns. In my database column
I have 2 mixing items and need to split out to 2 columns. Normally I have to write a query and change parameter
and run another query.
For example a database column with average number and range number.
Thanks
Daniel
Can you post some DDL, sample data and expected results?
AMB
|||
Hai,
Can you try the below query, and let me know that, it relates to your requirement or not:
DECLARE @.Columns varchar(1000)
SET @.Columns = ''
-- Create a temporary table.
CREATE TABLE #TempTable(Items varchar(50))
INSERT INTO #TempTable(Items) VALUES('A')
INSERT INTO #TempTable(Items) VALUES('A')
INSERT INTO #TempTable(Items) VALUES('A')
INSERT INTO #TempTable(Items) VALUES('B')
INSERT INTO #TempTable(Items) VALUES('B')
INSERT INTO #TempTable(Items) VALUES('B')
INSERT INTO #TempTable(Items) VALUES('C')
INSERT INTO #TempTable(Items) VALUES('C')
INSERT INTO #TempTable(Items) VALUES('D')
INSERT INTO #TempTable(Items) VALUES('D')
-- Before
SELECT * FROM #TempTable
-- Make a column list
SELECT
@.Columns = @.Columns + '[' + Items + '], '
FROM #TempTable
GROUP BY Items
-- Check the column values exits or not.
IF ( @.Columns IS NOT NULL ) AND ( @.Columns <> '' )
BEGIN
DECLARE @.Query nvarchar(1000)
SELECT @.Columns = SUBSTRING(@.Columns,1, LEN(@.Columns)-1)
SELECT @.Query = '
SELECT
*
FROM
(
SELECT
Items
FROM #TempTable
) AS Dummy
PIVOT
(
MAX(Items)
FOR Items IN (' + @.Columns + ')
)AS PvtTable'
EXEC(@.Query)
END
-- Drop the temporary table.
DROP TABLE #TempTable
Please clarify If I did any wrong.
Regards,
Kiran.Y
|||Perhaps something like:
SET NOCOUNT ON
DECLARE @.MyTable table
( RowID int IDENTITY,
MyGroup int,
MyValue decimal(10,2)
)
INSERT INTO @.MyTable VALUES ( 1, 25 )
INSERT INTO @.MyTable VALUES ( 2, 5 )
INSERT INTO @.MyTable VALUES ( 1, 10 )
INSERT INTO @.MyTable VALUES ( 1, 15 )
INSERT INTO @.MyTable VALUES ( 1, 4 )
INSERT INTO @.MyTable VALUES ( 2, 6 )
INSERT INTO @.MyTable VALUES ( 2, 11 )
INSERT INTO @.MyTable VALUES ( 2, 0 )
INSERT INTO @.MyTable VALUES ( 1, 12 )
SELECT
Average = cast( avg( MyValue ) AS decimal(10,2)),
Range = ( cast( min( MyValue ) AS varchar(10)) + '-' +
cast( max( MyValue ) AS varchar(10)))
FROM @.MyTable
GROUP BY MyGroup
Average Range
13.20 4.00-25.00
5.50 0.00-11.00
|||
Hi Kiran
Thanks for answering my email. To clarify this below are my tables and columns and my query
Table: Item Stat_label Stat_value
column: Pack ID Stat_label_ID Stat_value_ID
Pack_Num Label ( has 2 rows Value
Ave and Range)
My query to list Pack_Num, Ave and it's value
SELECT Item.Pack_Num, Stat_label.Label, Stat_value.Value
FROM Item, Stat_label, Stat_value
WHERE Item.packID=Stat_label.Stat_label_ID AND
Stat_label.Stat_lavel_ID=Stat_value.Stat_value_ID
AND Stat_label.Label= Ave
My question: I want a query to list Pack_Num, Ave, Range and value
How can I do it?
That's mean this query need to split the Stat_label and list another
column name"Range".
Thanks
Daniel
If you are using SQL 2005, look into the PIVOT function.
If you are using SQL 2000, explore using CASE.
Maybe these articles will help:
Pivot Tables -A simple way to perform crosstab operations
http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1131829,00.html
Pivot Tables - How to rotate a table in SQL Server
http://support.microsoft.com/default.aspx?scid=kb;en-us;175574
Pivot Tables -Dynamic Cross-Tabs
http://www.sqlteam.com/item.asp?ItemID=2955
Pivot Tables - Crosstab Pivot-table Workbench
http://www.simple-talk.com/sql/t-sql-programming/crosstab-pivot-table-workbench/
|||
Thanks all
I can not use "insert" because my account for this is read only and I avoid to list everything in a column and and use Excel pivot to summary.
Daniel
|||
Daniel,
If you would carefully examine the code provided, you will see that the INSERT statements are only building a sample table so that we could demonstrate a query suggestion.
You didn't bother to provide the table DDL, or sample data, so we have to waste our time creating sample data for you. and apparently, you can't read and understand example code.
|||
This may be closer to what you are hoping to find:
SELECT
i.Pack_Num,
sl.Stat_Label,
Average = cast( avg( sv.Stat_Value ) AS decimal(10,2)),
Range = ( cast( min( sv.Stat_Value ) AS varchar(10)) + '-' +
cast( max( sv.Stat_Value ) AS varchar(10)))
FROM Item i
JOIN Stat_Label sl
ON i.Pack_ID = sl.Stat_Label_ID
JOIN Stat_Value sv
ON sl.Stat_Label_ID = sv.Stat_Value_ID
WHERE sl.Label = 'Ave'
GROUP BY
i.Pack_Num,
sl.Stat_Label
|||
Thanks Anrnie but It is not working
Error at Average= cast......
Error at Range= (cast......
My Average and Range are decimal, no need cast
Do I have to declare a temp table?
Daniel
|||
Actually, it appears that the Stat_Value is most most likely a varchar().
Before we can help you any further, please post the table DDL and some sample data in the form of INSERT statements. Please refer to this link for help in preparing your material.
|||
Can SQL query create a new column or not?. DO NOT want to make a temp table.
Thanks
Daniel
|||
Can TSQL create a new column at the output?
If not I need 2 select statement but how to joint them? Can not use EXCEPT in TSQL? Tried to use UNION but
the results in one column.
It's complicated with creating a temp table since I do not know how to insert to temp table from database.
Thanks
Daniel
sql
Tuesday, March 20, 2012
query to retrieve the columns that are null in a table
I need help to build a query that shows me how many columns inside a range on columns are null.
Example: quantity1;quantity2;quantity3;quantity4;quantity5; quantity6;quantity7;
Which columns are null?
Thanks in advanceHi Teixeira,
I'm not sure what you are asking. If you could supply a table creation script some test data, and what the "result" should be based on the test data, that would help enormously.
Thanks,
Cat|||USE [myDB]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[books](
[book_id] [int] IDENTITY(1,1) NOT NULL,
[book_description] [nvarchar](max) COLLATE Latin1_General_CI_AS NULL,
[quantity1] [decimal](18, 2) NOT NULL,
[quantity2] [decimal](18, 2) NULL,
[quantity3] [decimal](18, 2) NULL,
[quantity4] [decimal](18, 2) NULL,
[quantity5] [decimal](18, 2) NULL,
[quantity6] [decimal](18, 2) NULL,
[quantity7] [decimal](18, 2) NULL,
[quantity8] [decimal](18, 2) NULL,
[quantity9] [decimal](18, 2) NULL,
[quantity10] [decimal](18, 2) NULL
this is my struture adapted.
based on this, i want to know which columns are not NULL, for my qyery result do not display for example 10 Quantity columns when i have just 3 that have quantities.|||Do you expect your query to return a single rowset, or is it possible to return multiple rows?|||yes!
It can return several rows.
but its not necessary to return columns that has null or empty values, because it would generated a lot of unnecessary columns in my datagrid display object|||I would change your structure from this:
CREATE TABLE [dbo].[books](
[book_id] [int] IDENTITY(1,1) NOT NULL,
[book_description] [nvarchar](max) COLLATE Latin1_General_CI_AS NULL,
[quantity1] [decimal](18, 2) NOT NULL,
[quantity2] [decimal](18, 2) NULL,
[quantity3] [decimal](18, 2) NULL,
[quantity4] [decimal](18, 2) NULL,
[quantity5] [decimal](18, 2) NULL,
[quantity6] [decimal](18, 2) NULL,
[quantity7] [decimal](18, 2) NULL,
[quantity8] [decimal](18, 2) NULL,
[quantity9] [decimal](18, 2) NULL,
[quantity10] [decimal](18, 2) NULL)
to this:
CREATE TABLE [dbo].[books](
[book_id] [int] IDENTITY(1,1) NOT NULL,
[book_description] [nvarchar](max) COLLATE Latin1_General_CI_AS NULL)
GO
CREATE TABLE [dbo].[bookquantity](
[book_id] [int] IDENTITY(1,1) NOT NULL,
[quantity] [decimal](18, 2) NOT NULL)
GO
ALTER TABLE [dbo].[bookquantity]
ADD CONSTRAINT FK_book (book_id) REFERENCE [books] (book_id)
GO
This way you are not tied to only 10 quantities and you can don't need to even store the NULL values.
If you can't change the structure of the table, I would suggest either creating a temp table with the above structure and populating it with the data from the master table so that you can weed out the nulls, or creating a single delimited string which the application can parse through. SQL can't really handle returning a result set with a variable number of fields.
The first suggestion would yield a result set like:
book_id quantity
------
1 12.70
1 33.45
1 9.00
The second suggestion would yield a result set like:
book_id quantity_list
--------
1 12.70|33.45|9.00
Hope this helps.
Cat|||I think you're both ideas are a good solution.
As i've some data already in the tables, normalize it more as you suggested would'd take me more time, but the second idea solves the problem perfectly.
Thanks for the help.
Teixeira
Query to reconcile data
Processdate ReportingPoint SerialNumber
When my customer starts construction on a part, they send a broadcast
to me that contains a date/time stamp, the serial number of the part,
and the reporting point "39".
Several hours, possibly days later, when the part is completed, they
send another broadcast containing a date/time stamp, the serial number
of the part, and the reporting point "111".
I need to create a query that can perform a basic reconciliation
between these two points. In other words, show me everything, by
serial number, that has a reporting point of "39", but no reporting
point of "111".
It seems that this would be easy, but I don't even know where to get
started.
Thank you,
Timselect field1,field2 from table
where reportingpoint = 39 and not exists
(select serial number from table as table2 where reportingpoint = 111
and table2.serialnumber =table.serialnumber)
"Timothy.Rybak@.gmail.com" wrote:
> I have a table with 3 columns:
> Processdate ReportingPoint SerialNumber
> When my customer starts construction on a part, they send a broadcast
> to me that contains a date/time stamp, the serial number of the part,
> and the reporting point "39".
> Several hours, possibly days later, when the part is completed, they
> send another broadcast containing a date/time stamp, the serial number
> of the part, and the reporting point "111".
> I need to create a query that can perform a basic reconciliation
> between these two points. In other words, show me everything, by
> serial number, that has a reporting point of "39", but no reporting
> point of "111".
> It seems that this would be easy, but I don't even know where to get
> started.
> Thank you,
> Tim
>|||Hey this is fun... Here is one way, I'm sure there are others:
select * from ConstructionStatus CS1 left join ConstructionStatus CS2
on CS1.SerNo = CS2.SerNo AND CS1.ReportingPoint = 39 AND
CS2.ReportingPoint != 39
where
CS2.ReportingPoint IS NULL
So, join two versions of the table: one with ReportingPoint 39 and the
other without ReportingPoint 39, and then look for the NULLS in the one
without ReportingPoint 39.
Hope that makes sense.
Timothy.Rybak@.gmail.com wrote:
> I have a table with 3 columns:
> Processdate ReportingPoint SerialNumber
> When my customer starts construction on a part, they send a broadcast
> to me that contains a date/time stamp, the serial number of the part,
> and the reporting point "39".
> Several hours, possibly days later, when the part is completed, they
> send another broadcast containing a date/time stamp, the serial number
> of the part, and the reporting point "111".
> I need to create a query that can perform a basic reconciliation
> between these two points. In other words, show me everything, by
> serial number, that has a reporting point of "39", but no reporting
> point of "111".
> It seems that this would be easy, but I don't even know where to get
> started.
> Thank you,
> Tim|||Isn't the virtually the same question that was asked and answered in the
programming group on 7/25, 8:21 AM, subject: Help with a Query?
Perhaps that same information still applies.
--
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
<Timothy.Rybak@.gmail.com> wrote in message
news:1154103522.720502.274630@.m73g2000cwd.googlegroups.com...
>I have a table with 3 columns:
> Processdate ReportingPoint SerialNumber
> When my customer starts construction on a part, they send a broadcast
> to me that contains a date/time stamp, the serial number of the part,
> and the reporting point "39".
> Several hours, possibly days later, when the part is completed, they
> send another broadcast containing a date/time stamp, the serial number
> of the part, and the reporting point "111".
> I need to create a query that can perform a basic reconciliation
> between these two points. In other words, show me everything, by
> serial number, that has a reporting point of "39", but no reporting
> point of "111".
> It seems that this would be easy, but I don't even know where to get
> started.
> Thank you,
> Tim
>|||MB and Jeff - Dead on accurate! Exactly what I needed!
Arnie - I guess it was close, but it was this issue of looking for a
serial that had one reporting point but not the other that was
troubling me. I never would have though to use the same table defined
two ways!
Also, as I have stated before, I am pretty new to SQL, but I am
learning every day. People like you make it fun and enjoyable!
Tim
Jeff Ericson wrote:
> select field1,field2 from table
> where reportingpoint = 39 and not exists
> (select serial number from table as table2 where reportingpoint = 111
> and table2.serialnumber =table.serialnumber)
> "Timothy.Rybak@.gmail.com" wrote:
> > I have a table with 3 columns:
> >
> > Processdate ReportingPoint SerialNumber
> >
> > When my customer starts construction on a part, they send a broadcast
> > to me that contains a date/time stamp, the serial number of the part,
> > and the reporting point "39".
> >
> > Several hours, possibly days later, when the part is completed, they
> > send another broadcast containing a date/time stamp, the serial number
> > of the part, and the reporting point "111".
> >
> > I need to create a query that can perform a basic reconciliation
> > between these two points. In other words, show me everything, by
> > serial number, that has a reporting point of "39", but no reporting
> > point of "111".
> >
> > It seems that this would be easy, but I don't even know where to get
> > started.
> >
> > Thank you,
> > Tim
> >
> >|||I'm glad that you are getting the help you need here -that what this
resource is about.
My point was to help you realize the commonality between the two situations
so that you could begin to extrapolate the things that you are learning.
Let us know if/when we can help you again. And don't forget to occasionally
stop in and share your growing knowledge and experience. After all, there is
always someone that knows less and needs help.
--
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
<Timothy.Rybak@.gmail.com> wrote in message
news:1154110530.612500.243460@.p79g2000cwp.googlegroups.com...
> MB and Jeff - Dead on accurate! Exactly what I needed!
> Arnie - I guess it was close, but it was this issue of looking for a
> serial that had one reporting point but not the other that was
> troubling me. I never would have though to use the same table defined
> two ways!
> Also, as I have stated before, I am pretty new to SQL, but I am
> learning every day. People like you make it fun and enjoyable!
> Tim
> Jeff Ericson wrote:
>> select field1,field2 from table
>> where reportingpoint = 39 and not exists
>> (select serial number from table as table2 where reportingpoint = 111
>> and table2.serialnumber =table.serialnumber)
>> "Timothy.Rybak@.gmail.com" wrote:
>> > I have a table with 3 columns:
>> >
>> > Processdate ReportingPoint SerialNumber
>> >
>> > When my customer starts construction on a part, they send a broadcast
>> > to me that contains a date/time stamp, the serial number of the part,
>> > and the reporting point "39".
>> >
>> > Several hours, possibly days later, when the part is completed, they
>> > send another broadcast containing a date/time stamp, the serial number
>> > of the part, and the reporting point "111".
>> >
>> > I need to create a query that can perform a basic reconciliation
>> > between these two points. In other words, show me everything, by
>> > serial number, that has a reporting point of "39", but no reporting
>> > point of "111".
>> >
>> > It seems that this would be easy, but I don't even know where to get
>> > started.
>> >
>> > Thank you,
>> > Tim
>> >
>> >
>
query to parse out values from one column into different columns
For (hypothetical) example:
There is an existing table with following info in three columns:
userid record recordtag
1 joe 1
1 j 2
1 jr 3
2 bob 1
2 a 2
2 sr 3
where recordtag indicates (1 for first name, 2 for middle initial, 3 for suffix)
I need to query these records for a report so it the output is:
userID firstname middleinitial suffix
1 joe j jr
2 bob a sr
What's the most efficient approach to create a query that will give me desired results? I have managed to create a very complex query that derives tables for each column I want to create and queries off of that derived table for the 'record' value based on the 'recordtag' values for a given 'userid'. The query is extremely slow, so I know there's some better way out there to get the results I want. Any help would be greatly appreciated. Thanks.Look up CROSSTAB queries in Books Online.select userid,
max(case recordtag when 1 then record end) as firstname,
max(case recordtag when 2 then record end) as middleinitial,
max(case recordtag when 3 then record end) as suffix
from [YourTable]
group by userid|||Thanks for the info. I'll let you know how I do.|||I incorporated the crosstab query into my code and the performance is stellar. Thanks for your help. !!
Monday, March 12, 2012
Query to get all user tables with columns
I tried to create a simple view as follows
CREATE VIEW V_ALL_USERTABLE_COLUMNS
AS
(
SELECT
OBJ.NAME as TableName,
COL.NAME as ColName,
TYP.NAME AS TYPE
FROM
SYSOBJECTS OBJ,
SYSCOLUMNS COL,
SYSTYPES TYP
WHERE
OBJ.TYPE = 'U'
AND OBJ.ID = COL.ID
AND COL.TYPE = TYP.TYPE
)
Combined with consistent naming conventions I will use this view to
easily find foreign keys; a la
SELECT *
FROM V_ALL_USERTABLE_COLUMNS
WHERE ColName LIKE ('%user_id')
There is something wrong with my view definition that I don't get
though; it doesn't return all the columns. I have a table with the
following definition
CREATE TABLE [dbo].[c_messages]
(
[cid] [int] IDENTITY (1, 1) NOT NULL ,
[touser_id] [int] NULL ,
[tosession_id] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
,
[fromuser_id] [int] NOT NULL ,
[message] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[message_read] [bit] NOT NULL ,
[logout] [bit] NULL
) ON [PRIMARY]
GO
The problem is that the select I used to define the view doesn't
return the touser_id column. I have sort of a sneaking suspicion that
the problem has to do with joining syscolumns.type to systypes.type,
but I don't know what to do instead (I'd really like to include the
type; it's useful if I ever changed the type of a primary key and want
to check that I also changed all the foreign keys).
Any help would be appreciated!Use the information schema rather than the system tables:
SELECT * FROM information_schema.columns
This format is much easier to use.
Your original query should work if you join on XTYPE rather than TYPE
but this is not recommended. In general you should avoid referencing
system tables directly.
--
David Portas
SQL Server MVP
--
Friday, March 9, 2012
query to fetch data
I have a table with two columns Task and Employee. It lists all the
tasks and the assigned employees. The same task will have multiple
roles with an employeename or 'manager' as the data.
If I have the following data
'sales', 'john'
'sales', 'manager'
'dev', 'manager'
'make_coffee', 'manager'
'browse', 'jane'
'browse', 'manager'
I need to get the rows wherever an employee is named (sales and browse
for example) and get manager for the rest.
I can make it in two queries. Look for not manager in one and then for
manager. Is there anyway to get them in a single query?
If I need to look for 'sales', I need to get 'john' and not 'manager'.
How to do that in a single query?
Another need is to list all tasks with assigned. So for the above, I
should get the following list
'sales', 'john'
'dev', 'manager'
'make_coffee', 'manager'
'browse', 'jane'
with two queries, I will get
'sales', 'john'
'browse', 'jane'
'dev', 'manager'
'make_coffee', 'manager'
which is ok. Order/sequence is not important.
TIA,
SreelathaThe code to create and insert data
CREATE TABLE tbl (
task nvarchar(20) NOT NULL,
employee nvarchar(20) NOT NULL)
GO
insert into tbl values('sales', 'john')
insert into tbl values('sales', 'manager')
insert into tbl values('dev', 'manager')
insert into tbl values('make_coffee', 'manager')
insert into tbl values('browse', 'jane')
insert into tbl values('browse', 'manager' )
go|||SELECT Task, Coalesce(Max(NullIf(Employee, 'Manager')), 'Manager')
FROM tbl
GROUP BY Task
Mr Tea
"sreelatha" <sreelatha@.hotmail.com> wrote in message
news:1110821575.186916.111250@.z14g2000cwz.googlegr oups.com...
> Hi,
> I have a table with two columns Task and Employee. It lists all the
> tasks and the assigned employees. The same task will have multiple
> roles with an employeename or 'manager' as the data.
> If I have the following data
> 'sales', 'john'
> 'sales', 'manager'
> 'dev', 'manager'
> 'make_coffee', 'manager'
> 'browse', 'jane'
> 'browse', 'manager'
> I need to get the rows wherever an employee is named (sales and browse
> for example) and get manager for the rest.
> I can make it in two queries. Look for not manager in one and then for
> manager. Is there anyway to get them in a single query?
> If I need to look for 'sales', I need to get 'john' and not 'manager'.
> How to do that in a single query?
> Another need is to list all tasks with assigned. So for the above, I
> should get the following list
> 'sales', 'john'
> 'dev', 'manager'
> 'make_coffee', 'manager'
> 'browse', 'jane'
> with two queries, I will get
> 'sales', 'john'
> 'browse', 'jane'
> 'dev', 'manager'
> 'make_coffee', 'manager'
> which is ok. Order/sequence is not important.
> TIA,
> Sreelatha
Monday, February 20, 2012
Query takes 3 mins to execute
the columns. millions of records exists in this table. when i run the below
query, it is taking nearly 3 minutes to execute. How can i minimise the query
time ?
SELECT TOP 100 count(*) as cntDuplicatePat, FIRST_NAME, SURNAME, ADDRESS_1,
POSTCODE, DATE_OF_BIRTH
From TBL_Patient
where Merged_Into_ID is NULL AND inactive='N' and
PATIENT_ID NOT IN
(SELECT PATIENT_ID_1 FROM TBL_PATIENT_DUPLICATES WHERE STATUS <> 2)
GROUP BY First_name, Surname, Address_1, Postcode, Date_of_birth
HAVING (COUNT(*) >=2)
Also i would like to know how a query time can be minimized (on what factors
the query time depends?)On Wed, 2 Aug 2006 06:02:02 -0700, Vikas
<Vikas@.discussions.microsoft.com> wrote:
>Hi all, Iam new to DBA. I have tables with created indexes on all most all of
>the columns. millions of records exists in this table. when i run the below
>query, it is taking nearly 3 minutes to execute. How can i minimise the query
>time ?
Creating indexes on most of the columns is not usually the answer.
Creating them on the right columns, and on the right sets of columns
(with the columns in the right order) requires understanding of what
queries will be doing.
>SELECT TOP 100 count(*) as cntDuplicatePat, FIRST_NAME, SURNAME, ADDRESS_1,
>POSTCODE, DATE_OF_BIRTH
> From TBL_Patient
> where Merged_Into_ID is NULL AND inactive='N' and
> PATIENT_ID NOT IN
> (SELECT PATIENT_ID_1 FROM TBL_PATIENT_DUPLICATES WHERE STATUS <> 2)
> GROUP BY First_name, Surname, Address_1, Postcode, Date_of_birth
> HAVING (COUNT(*) >=2)
>Also i would like to know how a query time can be minimized (on what factors
>the query time depends?)
Using TOP without ORDER BY makes little sense. I would either drop
the TOP 100, or add "ORDER BY cntDuplicatePat DESC".
I would not expect indexing of TBL_Patient to help much with this
query. The only way it might is if a very small percentage of
patients were active, or a very small percentage satisfied the "
Merged_Into_ID is NULL" test.
However, indexing of TBL_PATIENT_DUPLICATES is another matter. How
many rows are in TBL_PATIENT_DUPLICATES? How many columns? How many
satisfy the test STATUS <> 2? Does it have an index on PATIENT_ID_1?
You might try a non-clustered index on the column pair (PATIENT_ID_1,
STATUS).
It probably will not perform any differently, but you could also try a
NOT EXISTS test in place of the IN.
SELECT count(*) as cntDuplicatePat,
FIRST_NAME, SURNAME, ADDRESS_1, POSTCODE, DATE_OF_BIRTH
FROM TBL_Patient as P
WHERE Merged_Into_ID is NULL
AND inactive='N'
AND NOT EXISTS
(SELECT * FROM TBL_PATIENT_DUPLICATES as D
WHERE P.PATIENT_ID = D.PATIENT_ID_1
AND STATUS <> 2)
GROUP BY First_name, Surname, Address_1, Postcode, Date_of_birth
Roy Harvey
Beacon Falls, CT|||Thanks Roy!
I could get some stuff from your side. I also want to know how to
design a database so that query time is minimized and also the updates are
faster. can you prefer any e-book or any single url please.
Vikas
"Roy Harvey" wrote:
> On Wed, 2 Aug 2006 06:02:02 -0700, Vikas
> <Vikas@.discussions.microsoft.com> wrote:
> >Hi all, Iam new to DBA. I have tables with created indexes on all most all of
> >the columns. millions of records exists in this table. when i run the below
> >query, it is taking nearly 3 minutes to execute. How can i minimise the query
> >time ?
> Creating indexes on most of the columns is not usually the answer.
> Creating them on the right columns, and on the right sets of columns
> (with the columns in the right order) requires understanding of what
> queries will be doing.
> >SELECT TOP 100 count(*) as cntDuplicatePat, FIRST_NAME, SURNAME, ADDRESS_1,
> >POSTCODE, DATE_OF_BIRTH
> > From TBL_Patient
> > where Merged_Into_ID is NULL AND inactive='N' and
> > PATIENT_ID NOT IN
> > (SELECT PATIENT_ID_1 FROM TBL_PATIENT_DUPLICATES WHERE STATUS <> 2)
> > GROUP BY First_name, Surname, Address_1, Postcode, Date_of_birth
> > HAVING (COUNT(*) >=2)
> >
> >Also i would like to know how a query time can be minimized (on what factors
> >the query time depends?)
> Using TOP without ORDER BY makes little sense. I would either drop
> the TOP 100, or add "ORDER BY cntDuplicatePat DESC".
> I would not expect indexing of TBL_Patient to help much with this
> query. The only way it might is if a very small percentage of
> patients were active, or a very small percentage satisfied the "
> Merged_Into_ID is NULL" test.
> However, indexing of TBL_PATIENT_DUPLICATES is another matter. How
> many rows are in TBL_PATIENT_DUPLICATES? How many columns? How many
> satisfy the test STATUS <> 2? Does it have an index on PATIENT_ID_1?
> You might try a non-clustered index on the column pair (PATIENT_ID_1,
> STATUS).
> It probably will not perform any differently, but you could also try a
> NOT EXISTS test in place of the IN.
> SELECT count(*) as cntDuplicatePat,
> FIRST_NAME, SURNAME, ADDRESS_1, POSTCODE, DATE_OF_BIRTH
> FROM TBL_Patient as P
> WHERE Merged_Into_ID is NULL
> AND inactive='N'
> AND NOT EXISTS
> (SELECT * FROM TBL_PATIENT_DUPLICATES as D
> WHERE P.PATIENT_ID = D.PATIENT_ID_1
> AND STATUS <> 2)
> GROUP BY First_name, Surname, Address_1, Postcode, Date_of_birth
> Roy Harvey
> Beacon Falls, CT
>|||Sorry, there are lots of participants here with a catalog of links to
articles and books, but I'm not one of them.
The place to start in database design is normalization. Until you
understand that, and follow it, and do it by reflex, any other attempt
to design for minimized query time is probably going to create more
problems than it answers. Once you have that, then most of it is
proper indexing and queries.
Good luck!
Roy
On Wed, 2 Aug 2006 07:48:01 -0700, Vikas
<Vikas@.discussions.microsoft.com> wrote:
>Thanks Roy!
> I could get some stuff from your side. I also want to know how to
>design a database so that query time is minimized and also the updates are
>faster. can you prefer any e-book or any single url please.
>Vikas|||Vikas wrote:
> Hi all, Iam new to DBA. I have tables with created indexes on all most all of
> the columns. millions of records exists in this table. when i run the below
> query, it is taking nearly 3 minutes to execute. How can i minimise the query
> time ?
> SELECT TOP 100 count(*) as cntDuplicatePat, FIRST_NAME, SURNAME, ADDRESS_1,
> POSTCODE, DATE_OF_BIRTH
> From TBL_Patient
> where Merged_Into_ID is NULL AND inactive='N' and
> PATIENT_ID NOT IN
> (SELECT PATIENT_ID_1 FROM TBL_PATIENT_DUPLICATES WHERE STATUS <> 2)
> GROUP BY First_name, Surname, Address_1, Postcode, Date_of_birth
> HAVING (COUNT(*) >=2)
> Also i would like to know how a query time can be minimized (on what factors
> the query time depends?)
I'm curious about one part of your WHERE clause:
PATIENT_ID NOT IN
(SELECT PATIENT_ID_1 FROM TBL_PATIENT_DUPLICATES WHERE STATUS <> 2)
Isn't this the same as:
PATIENT_ID IN
(SELECT PATIENT_ID_1 FROM TBL_PATIENT_DUPLICATES WHERE STATUS = 2)
Written the first way, you're most likely looking at an index or table
scan, whereas the second method will, assuming "status = 2" is selective
enough, use an index seek.
Also, if the second method is true, you might consider doing this as an
INNER JOIN instead of an IN.
--
Tracy McKibben
MCDBA
http://www.realsqlguy.com|||On Thu, 03 Aug 2006 08:55:52 -0500, Tracy McKibben
<tracy@.realsqlguy.com> wrote:
>I'm curious about one part of your WHERE clause:
> PATIENT_ID NOT IN
> (SELECT PATIENT_ID_1 FROM TBL_PATIENT_DUPLICATES WHERE STATUS <> 2)
>Isn't this the same as:
> PATIENT_ID IN
> (SELECT PATIENT_ID_1 FROM TBL_PATIENT_DUPLICATES WHERE STATUS = 2)
>Written the first way, you're most likely looking at an index or table
>scan, whereas the second method will, assuming "status = 2" is selective
>enough, use an index seek.
>Also, if the second method is true, you might consider doing this as an
>INNER JOIN instead of an IN.
Suppose there is NO row in TBL_PATIENT_DUPLICATES with a specific
PATIEND_ID. With the original version the NOT IN will be satisfied.
With the alternate version it will not be satisfied.
Roy Harvey
BeacoN Falls, CT|||Roy Harvey wrote:
> On Thu, 03 Aug 2006 08:55:52 -0500, Tracy McKibben
> <tracy@.realsqlguy.com> wrote:
>> I'm curious about one part of your WHERE clause:
>> PATIENT_ID NOT IN
>> (SELECT PATIENT_ID_1 FROM TBL_PATIENT_DUPLICATES WHERE STATUS <> 2)
>> Isn't this the same as:
>> PATIENT_ID IN
>> (SELECT PATIENT_ID_1 FROM TBL_PATIENT_DUPLICATES WHERE STATUS = 2)
>> Written the first way, you're most likely looking at an index or table
>> scan, whereas the second method will, assuming "status = 2" is selective
>> enough, use an index seek.
>> Also, if the second method is true, you might consider doing this as an
>> INNER JOIN instead of an IN.
> Suppose there is NO row in TBL_PATIENT_DUPLICATES with a specific
> PATIEND_ID. With the original version the NOT IN will be satisfied.
> With the alternate version it will not be satisfied.
> Roy Harvey
> BeacoN Falls, CT
Doh! Makes perfect sense, thanks...
Tracy McKibben
MCDBA
http://www.realsqlguy.com
Query table based on multiple keys
I am having some confusion about how to formulate this particular
query.
I have 2 tables. Table A has 4 columns say a1,a2,a3,a4 with the
columns a1,a2,a4 forming the primary key. Table B again has 3 columns
with b1,b2,b3,b4 and like before, b1,b2 and b4 form the primary key.
All columns are of the same datatype in both tables. Now I want to get
rows from table A which are not present in table B. Whats the best way
of doing this?
Thanks
--
Posted using the http://www.dbforumz.com interface, at author's request
Articles individually checked for conformance to usenet standards
Topic URL: http://www.dbforumz.com/General-Dis...pict235166.html
Visit Topic URL to contact author (reg. req'd). Report abuse: http://www.dbforumz.com/eform.php?p=815725I'm no expert, so this probably isn't the most efficient way to do
this, but I think this will work:
select A.* from A, B
where A.a1 *= B.b1
and A.a2 *= B.b2
and A.a4 *= B.b4
and B.b1 is null
--Richard|||SELECT a1, a2, a3, a4
FROM A
WHERE NOT EXISTS
(SELECT *
FROM B
WHERE A.a1 = B.b1
AND A.a2 = B.b2
AND A.a3 = B.b3
AND A.a4*= B.b4 );|||
--CELKO-- wrote:
> SELECT a1, a2, a3, a4
> FROM A
> WHERE NOT EXISTS
> (SELECT *
> FROM B
> WHERE A.a1 = B.b1
> AND A.a2 = B.b2
> AND A.a3 = B.b3
> AND A.a4*= B.b4 );
Yeah, that works better than my version. I just tested a little more
and realized that mine doesn't actually do what I expected, but I can't
figure out why not.
--Richard|||--CELKO-- (jcelko212@.earthlink.net) writes:
> SELECT a1, a2, a3, a4
> FROM A
> WHERE NOT EXISTS
> (SELECT *
> FROM B
> WHERE A.a1 = B.b1
> AND A.a2 = B.b2
> AND A.a3 = B.b3
> AND A.a4*= B.b4 );
What is that *= doing on the last row?
The requirements were somewhat ambiguous, but one of these should do:
SELECT a1, a2, a3, a4
FROM A
WHERE NOT EXISTS
(SELECT *
FROM B
WHERE A.a1 = B.b1
AND A.a2 = B.b2
AND A.a4 = B.b4 );
(Rows identified by keys, the value in the non-key column a3/b3 may
be different.)
SELECT a1, a2, a3, a4
FROM A
WHERE NOT EXISTS
(SELECT *
FROM B
WHERE A.a1 = B.b1
AND A.a2 = B.b2
AND A.a4 = B.b4
AND A.a3 = B.b3 );
(Rows may be in both tables, but may have a difference in a3/b3.)
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||blueghost73@.yahoo.com (blueghost73@.yahoo.com) writes:
> I'm no expert, so this probably isn't the most efficient way to do
> this, but I think this will work:
> select A.* from A, B
> where A.a1 *= B.b1
> and A.a2 *= B.b2
> and A.a4 *= B.b4
> and B.b1 is null
*= is a older form of outer join which has all sorts of funny
quirkes with it. I am not going to find why this does not work.
Use the new ANSI syntax instead:
select A.*
from A
left join B ON A.a1 = B.b1
and A.a2 = B.b2
and A.a4 = B.b4
where and B.b1 is null
But I much prefer NOT EXISTS for this type of query, as it much better
expresses what you are looking for.
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||>> What is that *= doing on the last row? <<
Arrrgh! Cut & paste error!
Query syntax for count comparison
I need the syntax of a query to compare count(Client) by Seq#, between Table1 and Table2.
Something like this (although this doesn't work):
Select Table1.Seq#
from Table1 inner join Table2 on Table1.Seq# = Table2.Seq#
where count (table1.Client) = count (table2.Client)
Is this possible? If so, please provide correct syntax.
Thank you!
It would be easier for us to understand your requirement, if you posted some
sample data to work with, and the expected resultset.
HTH,
Vyas, MVP (SQL Server)
http://vyaskn.tripod.com/
Is .NET important for a database professional?
http://vyaskn.tripod.com/poll.htm
"Ysandre" <ysandre@.hotmail.com> wrote in message
news:2DFCF9B8-D4C6-4330-932A-678B0687FC86@.microsoft.com...
I have 2 tables, with 2 columns each: Seq# and Client.
I need the syntax of a query to compare count(Client) by Seq#, between
Table1 and Table2.
Something like this (although this doesn't work):
Select Table1.Seq#
from Table1 inner join Table2 on Table1.Seq# = Table2.Seq#
where count (table1.Client) = count (table2.Client)
Is this possible? If so, please provide correct syntax.
Thank you!
|||Take a look at FULL OUTER JOIN in SQL Server Books Online. In simple cases
similar to yours, one can use it to compare data across different tables.
Anith
Query Syntax
columns. I need to have 30 of the columns in a query using a select
statement. Since many of the columns are prefixed 'cc', I'd like to use a
wildcard, instead of typing out each column name. Is this possible? For
example, select cc* from table, or select cc% from table.
Thanks
steve.
No. Either select * from , or specify column names. If this is a repeated
work, create a view with the 30 columns and you can select * from the view.
"molsonexpert" <imdrunk@.work.ca> wrote in message
news:utISCBGkEHA.3664@.TK2MSFTNGP12.phx.gbl...
> I like some help on the syntax for a query: I have a table that has about
50
> columns. I need to have 30 of the columns in a query using a select
> statement. Since many of the columns are prefixed 'cc', I'd like to use a
> wildcard, instead of typing out each column name. Is this possible? For
> example, select cc* from table, or select cc% from table.
> Thanks
> steve.
>
|||> No. Either select * from
Ugh, in a production query? IMHO, this is not good advice at all, not only
because of the SELECT * alone, but also because he's going to retrieve 20
columns of data he has no interest in.
How about:
SELECT COLUMN_NAME + ', '
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='table name'
AND COLUMN_NAME LIKE 'cc%'
Then you can take that result from the results pane, and paste it into your
query (removing the trailing comma).
http://www.aspfaq.com/
(Reverse address to reply.)
|||molsonexpert wrote:
> I like some help on the syntax for a query: I have a table that has
> about 50 columns. I need to have 30 of the columns in a query using a
> select statement. Since many of the columns are prefixed 'cc', I'd
> like to use a wildcard, instead of typing out each column name. Is
> this possible? For example, select cc* from table, or select cc% from
> table.
> Thanks
> steve.
Or use Query Analyzer. Right click on the table and pick the option to
script a SELECT to a new window and trim those results.
David G.
|||Perfect. Thanks, Aaron. By the way, can anyone suggest a good book for SQL,
particularly SQL scripting? SQL help and BOL aren't bad, but I'd like a
reference manual as well. Thanks again.
steve.
"Aaron [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:OmqxikGkEHA.632@.TK2MSFTNGP12.phx.gbl...
> Ugh, in a production query? IMHO, this is not good advice at all, not
only
> because of the SELECT * alone, but also because he's going to retrieve 20
> columns of data he has no interest in.
> How about:
> SELECT COLUMN_NAME + ', '
> FROM INFORMATION_SCHEMA.COLUMNS
> WHERE TABLE_NAME='table name'
> AND COLUMN_NAME LIKE 'cc%'
> Then you can take that result from the results pane, and paste it into
your
> query (removing the trailing comma).
> --
> http://www.aspfaq.com/
> (Reverse address to reply.)
>
|||http://www.aspfaq.com/2423
http://www.aspfaq.com/
(Reverse address to reply.)
"molsonexpert" <imdrunk@.work.ca> wrote in message
news:eBp8JVPkEHA.1348@.TK2MSFTNGP15.phx.gbl...
> Perfect. Thanks, Aaron. By the way, can anyone suggest a good book for
SQL,[vbcol=seagreen]
> particularly SQL scripting? SQL help and BOL aren't bad, but I'd like a
> reference manual as well. Thanks again.
> steve.
> "Aaron [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
> news:OmqxikGkEHA.632@.TK2MSFTNGP12.phx.gbl...
> only
20
> your
>
Query Syntax
columns. I need to have 30 of the columns in a query using a select
statement. Since many of the columns are prefixed 'cc', I'd like to use a
wildcard, instead of typing out each column name. Is this possible? For
example, select cc* from table, or select cc% from table.
Thanks
steve.No. Either select * from , or specify column names. If this is a repeated
work, create a view with the 30 columns and you can select * from the view.
"molsonexpert" <imdrunk@.work.ca> wrote in message
news:utISCBGkEHA.3664@.TK2MSFTNGP12.phx.gbl...
> I like some help on the syntax for a query: I have a table that has about
50
> columns. I need to have 30 of the columns in a query using a select
> statement. Since many of the columns are prefixed 'cc', I'd like to use a
> wildcard, instead of typing out each column name. Is this possible? For
> example, select cc* from table, or select cc% from table.
> Thanks
> steve.
>|||> No. Either select * from
Ugh, in a production query? IMHO, this is not good advice at all, not only
because of the SELECT * alone, but also because he's going to retrieve 20
columns of data he has no interest in.
How about:
SELECT COLUMN_NAME + ', '
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='table name'
AND COLUMN_NAME LIKE 'cc%'
Then you can take that result from the results pane, and paste it into your
query (removing the trailing comma).
--
http://www.aspfaq.com/
(Reverse address to reply.)|||molsonexpert wrote:
> I like some help on the syntax for a query: I have a table that has
> about 50 columns. I need to have 30 of the columns in a query using a
> select statement. Since many of the columns are prefixed 'cc', I'd
> like to use a wildcard, instead of typing out each column name. Is
> this possible? For example, select cc* from table, or select cc% from
> table.
> Thanks
> steve.
Or use Query Analyzer. Right click on the table and pick the option to
script a SELECT to a new window and trim those results.
--
David G.|||Perfect. Thanks, Aaron. By the way, can anyone suggest a good book for SQL,
particularly SQL scripting? SQL help and BOL aren't bad, but I'd like a
reference manual as well. Thanks again.
steve.
"Aaron [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:OmqxikGkEHA.632@.TK2MSFTNGP12.phx.gbl...
> > No. Either select * from
> Ugh, in a production query? IMHO, this is not good advice at all, not
only
> because of the SELECT * alone, but also because he's going to retrieve 20
> columns of data he has no interest in.
> How about:
> SELECT COLUMN_NAME + ', '
> FROM INFORMATION_SCHEMA.COLUMNS
> WHERE TABLE_NAME='table name'
> AND COLUMN_NAME LIKE 'cc%'
> Then you can take that result from the results pane, and paste it into
your
> query (removing the trailing comma).
> --
> http://www.aspfaq.com/
> (Reverse address to reply.)
>|||http://www.aspfaq.com/2423
--
http://www.aspfaq.com/
(Reverse address to reply.)
"molsonexpert" <imdrunk@.work.ca> wrote in message
news:eBp8JVPkEHA.1348@.TK2MSFTNGP15.phx.gbl...
> Perfect. Thanks, Aaron. By the way, can anyone suggest a good book for
SQL,
> particularly SQL scripting? SQL help and BOL aren't bad, but I'd like a
> reference manual as well. Thanks again.
> steve.
> "Aaron [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
> news:OmqxikGkEHA.632@.TK2MSFTNGP12.phx.gbl...
> > > No. Either select * from
> >
> > Ugh, in a production query? IMHO, this is not good advice at all, not
> only
> > because of the SELECT * alone, but also because he's going to retrieve
20
> > columns of data he has no interest in.
> >
> > How about:
> >
> > SELECT COLUMN_NAME + ', '
> > FROM INFORMATION_SCHEMA.COLUMNS
> > WHERE TABLE_NAME='table name'
> > AND COLUMN_NAME LIKE 'cc%'
> >
> > Then you can take that result from the results pane, and paste it into
> your
> > query (removing the trailing comma).
> >
> > --
> > http://www.aspfaq.com/
> > (Reverse address to reply.)
> >
> >
>
Query Syntax
columns. I need to have 30 of the columns in a query using a select
statement. Since many of the columns are prefixed 'cc', I'd like to use a
wildcard, instead of typing out each column name. Is this possible? For
example, select cc* from table, or select cc% from table.
Thanks
steve.No. Either select * from , or specify column names. If this is a repeated
work, create a view with the 30 columns and you can select * from the view.
"molsonexpert" <imdrunk@.work.ca> wrote in message
news:utISCBGkEHA.3664@.TK2MSFTNGP12.phx.gbl...
> I like some help on the syntax for a query: I have a table that has about
50
> columns. I need to have 30 of the columns in a query using a select
> statement. Since many of the columns are prefixed 'cc', I'd like to use a
> wildcard, instead of typing out each column name. Is this possible? For
> example, select cc* from table, or select cc% from table.
> Thanks
> steve.
>|||> No. Either select * from
Ugh, in a production query? IMHO, this is not good advice at all, not only
because of the SELECT * alone, but also because he's going to retrieve 20
columns of data he has no interest in.
How about :
SELECT COLUMN_NAME + ', '
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='table name'
AND COLUMN_NAME LIKE 'cc%'
Then you can take that result from the results pane, and paste it into your
query (removing the trailing comma).
http://www.aspfaq.com/
(Reverse address to reply.)|||molsonexpert wrote:
> I like some help on the syntax for a query: I have a table that has
> about 50 columns. I need to have 30 of the columns in a query using a
> select statement. Since many of the columns are prefixed 'cc', I'd
> like to use a wildcard, instead of typing out each column name. Is
> this possible? For example, select cc* from table, or select cc% from
> table.
> Thanks
> steve.
Or use Query Analyzer. Right click on the table and pick the option to
script a SELECT to a new window and trim those results.
David G.|||Perfect. Thanks, Aaron. By the way, can anyone suggest a good book for SQL,
particularly SQL scripting? SQL help and BOL aren't bad, but I'd like a
reference manual as well. Thanks again.
steve.
"Aaron [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:OmqxikGkEHA.632@.TK2MSFTNGP12.phx.gbl...
> Ugh, in a production query? IMHO, this is not good advice at all, not
only
> because of the SELECT * alone, but also because he's going to retrieve 20
> columns of data he has no interest in.
> How about :
> SELECT COLUMN_NAME + ', '
> FROM INFORMATION_SCHEMA.COLUMNS
> WHERE TABLE_NAME='table name'
> AND COLUMN_NAME LIKE 'cc%'
> Then you can take that result from the results pane, and paste it into
your
> query (removing the trailing comma).
> --
> http://www.aspfaq.com/
> (Reverse address to reply.)
>|||http://www.aspfaq.com/2423
http://www.aspfaq.com/
(Reverse address to reply.)
"molsonexpert" <imdrunk@.work.ca> wrote in message
news:eBp8JVPkEHA.1348@.TK2MSFTNGP15.phx.gbl...
> Perfect. Thanks, Aaron. By the way, can anyone suggest a good book for
SQL,
> particularly SQL scripting? SQL help and BOL aren't bad, but I'd like a
> reference manual as well. Thanks again.
> steve.
> "Aaron [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
> news:OmqxikGkEHA.632@.TK2MSFTNGP12.phx.gbl...
> only
20[vbcol=seagreen]
> your
>